This time, let’s figure out how to replace all the identical 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 we will change only the first substring abc.

There are at least two optimal solutions to this problem — use regular expressions or use split and join methods.

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

Regular Expressions

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

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 — 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 intelligent things with our creations, and we’ll prevent this scenario.

We need a function that will format the search argument:

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

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); 
};

Blog