How to Replace All Occurrences of a String in JavaScript
On this page, you can find the fast-solutions on how to replace all the occurrences of a string in JavaScript. Read it and find the simplest solution.
In this snippet, we are going to guide you in learning the proper way to replace all occurrences of a string in JavaScript. Note that modern JavaScript (ES2021) includes a built-in String.prototype.replaceAll() method, which is the recommended approach for most cases. The following sections cover alternative methods for legacy environments or specific use cases.
Using Regular Expressions
In general, the JavaScript <kbd class="highlighted">replace()</kbd> function is used for replacing.
Let’s start from the most straightforward way: combining the <kbd class="highlighted">replace()</kbd> function with a <kbd class="highlighted">regular expression (regexp)</kbd>.
The following regexp implements a case-sensitive substitution:
javascript regex implementation
String.replace(/<TERM>/g, '')In the next example, all the occurrences of the word “animals” are substituted in the string phrase:
JavaScript substring example
For performing a case-insensitive replacement, you need to use the <kbd class="highlighted">gi</kbd> option in the regexp, as follows:
javascript regexp implementation
String.replace(/<TERM>/gi, '')The example looks like this:
JavaScript regexp implementation
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 escape the string by applying the following function:
javascript regex special characters
const escapeRegExp = (string) => {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}Using Split and Join
There is also an alternative solution: using two JavaScript functions. Albeit this solution is slower than regex, it can be quite handy as well.
The first function is <kbd class="highlighted">split()</kbd>, targeted at truncating a string when it finds a pattern, and returning an array with the tokens, as follows:
JavaScript split example
Then, you need to join the tokens in a new string without a separator:
JavaScript join example
const stripped = tokens.join('') // "I love ! Animals are cute"A Custom Iterative Search and Replace
When you supply a string as the first argument of the <kbd class="highlighted">replace()</kbd> function, it replaces only the first occurrence. Using that information, you can create a function that iteratively goes through the whole string until all matches are replaced.
The replacement of all matches with a case-sensitive search is demonstrated here:
JavaScript iterative replace
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 the first match and continue iterating
while (str.indexOf(searchString) !== -1) {
str = str.replace(searchString, replaceString);
}
return str;
}
// usage:
var str = 'welcome world! welcome people! Welcome hello!';
console.log(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 <kbd class="highlighted">String.prototype.replaceAll()</kbd>, which can replace all string occurrences straightforwardly. Hence, we recommend relying on this method.