Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading