Join the string with same separator used to split

后端 未结 5 1242
执笔经年
执笔经年 2021-01-19 15:40

I have a string that need to be split with a regular expression for applying some modifications.

eg:

const str = \"Hello+Beautiful#World\";
const spl         


        
5条回答
  •  后悔当初
    2021-01-19 16:40

    you can rejoin the array by finding the indexes that where the matching happened on the string

    const str = "Hello+Beautiful#World";
    const regex = /[\+#]/g;
    const splited = str.split(regex);
    console.log(splited);
    
    
    //join
    let x = '';
    let i=0;
    while ((match = regex.exec(str)) != null) {
        x = x + splited[i] + "00" + (i+1) + str[match.index];
        i++;
    }
    x = x + splited[splited.length-1] + "00" + (i+1);
    console.log(x);

提交回复
热议问题