Categories
JavaScript Answers

How to replace multiple strings at once with JavaScript?

Spread the love

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 = ["&lt;", "&gt;", "<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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *