How to Replace all Occurrences of a String in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 08 20212 min read

banner

Photo by Nicole Geri

Replace all Occurrences of a String in JavaScript #

To replace all occurrences of a string, use the replace() method, passing it a regular expression with the g (global search) flag. For example, str.replace(/old/g, 'new') returns a new string where all occurrences of old are replaced with new.

index.js
const str = 'old old world'; const replacedAll = str.replace(/old/g, 'new'); console.log(replacedAll); // ๐Ÿ‘‰๏ธ new new world

We pass the following 2 parameters to the String.replace method:

  1. A regular expression to match. Notice that we use the g (global) flag to specify that we want to match all occurrences and not just the first one
  2. A replacement string

If you need to match a substring in a case insensitive way, add the i flag after the g flag.

index.js
const str = 'old OLD world'; const replacedAll = str.replace(/old/gi, 'new'); console.log(replacedAll); // ๐Ÿ‘‰๏ธ new new world

The i flag enables case-insensitive search. For a complete list of regex flags, check out this table in the MDN docs.

The replace method does not change the original string, instead it returns a new string with the matches replaced. Strings are immutable in JavaScript.

An alternative approach is to use the newer replaceAll method.

To replace all occurrences of a string, call the replaceAll() method, passing it the string to be replaced and the replacement as parameters. For example, str.replaceAll('old', 'new') returns a new string where all occurrences of old are replaced with new.

index.js
// Not Supported in IE 6-11 const str = 'old old world'; const replacedAll = str.replaceAll('old', 'new'); console.log(replacedAll); // ๐Ÿ‘‰๏ธ new new world

The 2 parameters we pass to the String.replaceAll method are:

  1. The string to be replaced
  2. The replacement string
The replaceAll method is not supported by Internet Explorer versions 6-11. If you have to support this browser, you can add a polyfill for the method, use babel to compile your code to an older version of JavaScript, or simply use the replace method instead.

If you have to replace all occurrences of a case insensitive string, you can pass a regular expression to the replaceAll method and use it just like we used the replace method.

index.js
const str = 'old old world'; const replacedAll = str.replaceAll(/old/gi, 'new'); console.log(replacedAll); // ๐Ÿ‘‰๏ธ new new world

There is no good reason to use replaceAll over replace in this scenario.

It takes the exact same parameters as the replace method, however it's supported by less browsers.

Anytime you pass a regular expression to the replaceAll method, you have to set the g (global) flag to match all occurrences, otherwise a TypeError is thrown.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee