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.
9 Comments
aamir khan · August 19, 2013 at 7:52 AM
Thanks for the tutorial , this helps
Nathaniel Inman · June 16, 2014 at 9:56 PM
Thanks, helps a lot! I’m throwing the following at the top of a lot of my experiments.
String.prototype.replaceAll=function(t,r){return this.split(t).join(r);};
Charlie Phillips · August 15, 2014 at 11:23 AM
Thanks Chris! Simpler than RegEx, yet works just as good and I love that you made it a prototype!
Denes Kellner · July 9, 2015 at 10:01 AM
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.
Chinthana · October 8, 2015 at 8:23 AM
i this is the easiest way to replace all occurrence.
Thaks for the valuable post.Keep it up….. 🙂
Alex · June 19, 2017 at 5:24 AM
https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript
and benchmark:
http://jsben.ch/LFfWA
Alex · September 13, 2017 at 11:10 AM
It depends on string, search/replace values and browser.
For example, my test http://jsben.ch/ebMdQ faster in FF for split, but your for regex. Although in Chrome vice versa.
Ikram Khan · July 25, 2018 at 3:53 PM
Thank you so much.
sean · August 19, 2019 at 6:17 PM
Wow, incredibly simple. Nicely done.