Join the string with same separator used to split

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

    When you place a pattern inside a capturing group, split will return the matched delimiters as even array items. So, all you need to do is modify the odd items:

    var counter=1;
    var str = "Hello+Beautiful#World";
    console.log(
      str.split(/([+#])/).map(function(el, index){
        return el + (index % 2 === 0 ? (counter++ + "").padStart(3, '0') : '');
      }).join("")
    );

提交回复
热议问题