Sometimes, we want to replace multiple strings at once with JavaScript.
In this article, we’ll look at how to replace multiple strings at once with JavaScript.
How to replace multiple strings at once with JavaScript?
To replace multiple strings at once with JavaScript, we can use the string replace
method.
For instance, we write
const findFor = ["<", ">", "\n"];
const replaceWith = ["<", ">", "<br/>"];
const originalString = "<strong>Hello World</strong> \n Let's code";
let modifiedString = originalString;
findFor.forEach(
(tag, i) =>
(modifiedString = modifiedString.replace(
new RegExp(tag, "g"),
replaceWith[i]
))
);
to call findFor.forEach
with a callback that replaces the tag
substring in modifiedString
with the replaceWith[i]
string.
i
is the index of the findFor
array being looped through.
We use the new RegExp(tag, "g")
regex to find all matches of tag
.
Conclusion
To replace multiple strings at once with JavaScript, we can use the string replace
method.