How to Replace All Occurrences of a String in JavaScript

To replace all occurrences of a string in JavaScript, you can use the String.prototype.replace() method with a global regular expression or another more modern approach is using the replaceAll() method.

Here's a short guide using both approaches:

Using replace() + Regular Expression

Syntax: str.replace(/searchString/g, 'newString') As an example, let's replace all instances of "cat" with "dog":

const sentence = "The cat sat on the cat mat.";
const newSentence = sentence.replace(/cat/g, "dog");
console.log(newSentence); // "The dog sat on the dog mat."

Using replaceAll()

This method was introduced in ES2021 and is supported on all modern browsers. Syntax: str.replaceAll(searchString, newString) Now, like the first example, let's replace all instances of "cat" with "dog":

const sentence = "The cat sat on the cat mat.";
const newSentence = sentence.replaceAll("cat", "dog");
console.log(newSentence); // "The dog sat on the dog mat."

Note: searchString can be a string or a global regular expression. This will be handy if you need to do something a little extra like case-insensitive replacing (which we will look at next.) Be aware that it will throw an error if it's not a global expression. This has caught me out before...

Case-Insensitive Replacement

Sometimes, you might need a case-insensitive replacement. You can add the i flag to the regular expression to perform a case-insensitive replacement.

Let's again replace "cat" with "dog", but this time ignoring the case:

const sentence = "The Cat sat on the cat mat.";
const newSentence = sentence.replace(/cat/gi, "dog");
console.log(newSentence); // "The dog sat on the dog mat."

Happy coding! ✌️

JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.