How to replace all identical substrings in a string with JavaScript

This time, let’s figure out how to replace all the same substrings in a particular string. Suppose we have a line:

var str = "Test abc test test abc test test test abc test test abc";

And our code should replace, for example, all the abc substrings in this line. Using the replace method does not work, because in this way we will replace only the very first substring abc.

There are at least two optimal solutions to this problem: the use of regular expressions and the methods split and join.

Attention! In the examples below, we will solve this problem by rewriting the methods built into JavaScript. This is not the best practice and is strongly not recommended for use in real projects. We will use it exclusively for demonstration purposes.

Method One – Regular Expressions

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

Method two – split and join

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.split(search).join(replacement);
};

As for performance, it is worth noting that the first solution works as much as twice as fast as the second.

However, there is a snag in the solution using regular expressions: it is assumed that the user will not use the characters reserved for regular expressions as the first parameter. Users are different and often do not do the most reasonable things with our creations, so we will not risk and prevent this scenario.

We need a function that will format the search argument:

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\]/g, "\$&");
}

All that remains is to call the escapeRegExp function in our String.prototype.replaceAll:

String.prototype.replaceAll = function(search, replacement) {
    search = escapeRegExp(search);
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};