Join the string with same separator used to split

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

    You could get the missing substrings by iterating the splitted value and check the parts.

    var string = "Hello++#+Beautiful#World",
        splitted = string.split(/[\+#]+/),
        start = 0,
        symbols = splitted.map((s, i, { [i + 1]: next }) => {
            var index = string.indexOf(next, start += s.length);
            if (index !== -1) {
                var sub = string.slice(start, index);
                start = index;
                return sub;
            }
            return '';
        });
    
    console.log(symbols);
    console.log(splitted.map((s, i) => s + symbols[i]).join(''));

提交回复
热议问题