I\'m trying to replace multiple words in a string with multiple other words. The string is \"I have a cat, a dog, and a goat.\"
However, this does not produce \"I ha
Use numbered items to prevent replacing again. eg
let str = "I have a %1, a %2, and a %3";
let pets = ["dog","cat", "goat"];
then
str.replace(/%(\d+)/g, (_, n) => pets[+n-1])
How it works:- %\d+ finds the numbers which come after a %. The brackets capture the number.
This number (as a string) is the 2nd parameter, n, to the lambda function.
The +n-1 converts the string to the number then 1 is subtracted to index the pets array.
The %number is then replaced with the string at the array index.
The /g causes the lambda function to be called repeatedly with each number which is then replaced with a string from the array.
In modern JavaScript:-
replace_n=(str,...ns)=>str.replace(/%(\d+)/g,(_,n)=>ns[n-1])