JavaScript – String.prototype.replaceAll()

Now Available in YourJS

For those of you who don’t know too much about regular expressions or just want to be able to replace every occurrence of a substring with something else, perhaps this definition for the replaceAll() function of all instances of String object will prove beneficial:

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

Yep, that’s it! No more code is necessary in order to make the following work as expected:

// Display:  Chriz Wezt
alert("Chris West".replaceAll("s", "z"));

// Display:  Peter Piker kicks kekkers.
alert("Peter Piper picks peppers.".replaceAll("p", "k"));

// Display:  Anteedeesestableeshmentareeaneesm
alert("Antidisestablishmentarianism".replaceAll("i", "ee"));

By default, this function also works with regular expressions. Regardless of the global flag being set for a regular expression, this function will replace each match that is found.