Join the string with same separator used to split

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

    Don't use split and join in this case. Use String.replace(), and return the modified strings:

    const str = "Hello+Beautiful#World";
    
    let counter = 1;
    const result = str.replace(/[^\+#]+/g, m =>
      `${m.trim()}${String(counter++).padStart(3, '0')}`
    );
    
    console.log(result);

    Another option, which might not fit all cases, is to split before the special characters using a lookahead, map the items, and join with an empty string:

    const str = "Hello+Beautiful#World";
    
    let counter = 1;
    const result = str.split(/(?=[+#])/)
      .map(s => `${s.trim()}${String(counter++).padStart(3, '0')}`)
      .join('')
    
    console.log(result);

提交回复
热议问题