refering to Replace words with array map
the answer is good, but I would like to add global replace to it.
const arrString = ["beginning=beginner", "leaves=leave", "sound=sounds"];
let string = "its beginner in the sounds leave";
arrString.forEach((mapString) => {
const stringArr = mapString.split("=");
string = string.replace(stringArr[1], stringArr[0]);
});
console.log("string", string);
I tried
string.replace(/stringArr[1]/p, stringArr[0]);
Tried it on a string having the same word 3 times.
not working, only the first is replaced.
2
Answers
To perform a global replace using a regular expression in JavaScript, you can use the g flag.
just modify your code
Just use
String::replaceAll()
, no need in a regular expression here. Also it’s confusing that you have your replacements reversed. Semantically I guess would be betterbeginner = (means replace beginner with) beginning
.If you want regexp anyway:
The regexp version seems a bit faster: