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
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);