javascript replace by regex match location

In this program I want to replace the 2 + in str respectively by array element. The solution below doesn’t work because the regex contains + and the array contains also +. How to do that kind of replacement by location then ?

let regex = /\+/gm;
let str = `abc+def+`;
let array = ["+", "test"];
let matches = [...str.matchAll(regex)][0];
for (let a of array.entries()) {
  console.log(a);
  str = str.replace(/\+/, a.toString())
  console.log(str);
}

>Solution :

The replacement argument of str.replace() can be a function. This can increment an array index to get the replacement.

let regex = /\+/g;
let str = `abc+def+`;
let array = ["+", "test"];
let index = 0;
str = str.replace(regex, () => array[index++]);
console.log(str);

Leave a Reply