Join the string with same separator used to split

后端 未结 5 1244
执笔经年
执笔经年 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:22

    My solution is to get the splitters then save them into an array and rejoin:

    function splitAndRejoin(){
        const str = "Hello+Beautiful#World";
        const splited = str.split(/[\+#]/);
        var spliterCharacter = [];
        for(var i = 0; i < str.length; i++){
            if(str[i] == "+" || str[i] == "#"){
                spliterCharacter.push(str[i]);
            }
        }
        var rejoin = "";
        for (i = 0; i <= spliterCharacter.length; i++) {
            if(i< spliterCharacter.length)
                rejoin += splited[i] + spliterCharacter[i];
            else
                rejoin += splited[i];
        }
        console.log(splited);
        console.log(spliterCharacter);
        console.log(rejoin); // Result
    }
    

提交回复
热议问题