How to Replace All Occurrences of a String in JavaScript

In this snippet, we are going to guide you in learning the proper way to replace all occurrences of a string in JavaScript.

Using Regular Expressions

In general, the JavaScript replace() function is used for replacing.

Let’s start from the most straightforward way: combining the replace() function with a regular expression (regexp).

The following regexp implements a case sensitive substitution:

String.replace(/<TERM>/g, '')

In the next example, all the occurrences of the word “animals” are substituted in the string phrase:

const phrase = 'I love animals! Animals are cute'
const stripped = phrase.replace(/animals/g, '')
console.log(stripped) //"I love ! Animals are cute"

For performing a case-insensitive replacement, you need to use the gi option in the regexp, as follows:

String.replace(/<TERM>/gi, '')

The example looks like this:

const phrase = 'I love animals! Animals are cute'
const stripped = phrase.replace(/animals/gi, '')
console.log(stripped) //"I love ! are cute"

Please, take into consideration that in case there are special characters inside the string, it may not work well with regular expressions. That’s why we recommend you to skip the string by applying the following function:

const outputRegExp = (string) => {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

Using Split and Joint

There is also an alternative solution: using two JavaScript functions. Albeit this solution is slower than the regex, it can be quite handy, as well.

The first function is split() targeted at truncating a string when it finds a pattern, and returning an array with the tokens, as follows:

const phrase = 'I love animals! Animals are cute';
const tokens = phrase.split('animals');
console.log(tokens); //["I love  ", "! Animals are great"]

Then, you need to join the tokens in a new string without the help of a separator:

const stripped = tokens.join('') //"I love ! Animals are great"

A Custom Recursive Search and Replace

When you supply the string as the first argument of the replace function, it replaces only the first occurrences of the string. Using that information, you can create a function, which recursively goes through the whole string investigating and replacing it until the overall matches are replaced.

The replacement of all matches with a case-sensitive search is demonstrated here:

String.prototype.replaceAll = function (searchString, replaceString) {
  var str = this;
  // there are no matches in string?
  if (str.indexOf(searchString) === -1) {
    // return string
    return str;
  }
  // replace and remove the first match, and perform another recursive search/replace
  return (str.replace(searchString, replaceString)).replaceAll(searchString, replaceString);
}
// usage:
str.replaceAll('welcome', 'hello');

// output: hello world! hello people! Welcome hello!

So, replacing all JavaScript string occurrences is not an easy job. Unfortunately, it is not possible to quickly generate regular expressions from a string at runtime, as you need to escape the special characters of the regex. Moreover, it’s overwhelming to deal with a regular expression for a simple replacement of strings.

Luckily, there exists String.prototype.replaceAll(), which can replace all the string occurrences straightforwardly. Hence, we recommend relying basically on this method.


Do you find this helpful?

Related articles