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.

6 Replies to “JavaScript – String.prototype.replaceAll()”

  1. Hah 🙂 Just did EXACTLY the same thing, with the very same name, and then, out of curiousity, I googled for it. Like quote, string dot prototype dot replaceAll. Tadaaaaaaa 🙂 That’s VERY funny, I mean, great minds think alike.

Leave a Reply

Your email address will not be published. Required fields are marked *