By Click Upvote

2009-07-17 17:53:46 8 Comments

I have this string:

"Test abc test test abc test test test abc test test abc"


str = str.replace('abc', '');

seems to only remove the first occurrence of abc in the string above. How can I replace all occurrences of it?


@Alireza 2017-06-06 13:39:22

Using RegExp in JavaScript could do the job for you, just simply do something like below, don't forget the /g after which standout for global:

var str ="Test abc test test abc test test test abc test test abc";
str = str.replace(/abc/g, '');

If you think of reuse, create a function to do that for you, but it's not recommended as it's only one line function, but again if you heavily get use of this, you can write something like this:

String.prototype.replaceAll = String.prototype.replaceAll || function(string, replaced) {
  return this.replace(new RegExp(string, 'g'), replaced);

and simply use it in your code over and over like below:

var str ="Test abc test test abc test test test abc test test abc";
str = str.replaceAll('abc', '');

But as I mention earlier, it won't make a huge difference in terms of lines to be written or performance, only caching the function may effect some faster performance on long strings and also a good practice of DRY code if you want to reuse.

@prime 2019-02-15 19:15:19

This can be achieved using Regex. Few combinations that might help someone,

var word = "this,\\ .is*a*test,    '.and? / only /     'a \ test?";
var stri = "This      is    a test         and only a        test";

To replace all non alpha characters,

console.log(word.replace(/([^a-z])/g,' ').replace(/ +/g, ' ')); 
Result: [this is a test and only a test]

To replace multiple continuous spaces with one space,

console.log(stri.replace(/  +/g,' ')); 
Result: [This is a test and only a test]

To replace all * characters,

Result: [this,\ .isatest,    '.and? / only /     'a  test?]

To replace question marks (?)

Result: [this,\ .is*a*test,    '.and# / only /     'a  test#]

To replace quotation marks,

Result: [this,\ .is*a*test,    #.and? / only /     #a  test?]

To replace all ' characters,

Result: [this\ .is*a*test    '.and? / only /     'a  test?]

To replace a specific word,

Result: [this,\ .is*a*,    '.and? / only /     'a  ?]

To replace back-slash,

Result: [this, .is*a*test,    '.and? / only /     'a  test?]

To replace forward slash,

Result: [this,\ .is*a*test,    '.and?  only      'a  test?]

To replace all spaces,

console.log(word.replace(/ /g,'#'));  
Result: [this,\*a*test,####'.and?#/#only#/#####'a##test?]

To replace dots,

Result: [this,\ #is*a*test,    '#and? / only /     'a  test?]

@Brijesh Kumar 2019-02-09 08:28:26

Simplest Solution -

let str = "Test abc test test abc test test test abc test test abc";

str = str.split(" ");
str = str.filter((ele, key)=> ele!=="abc")
str = str.join(" ")

Or Simply - 

str = str.split(" ").filter((ele, key) => ele != "abc").join(" ")

@Yash 2019-02-07 13:49:05

Best solution, in order to replace any Character we use these indexOf(), includes(), substring() functions to replace matched String with the provided String in the Current String.

  • String.indexOf() function is to find the nth match index position.
  • String.includes() method determines whether one string may be found within another string, returning true or false as appropriate.
  • String.substring() function is to get the parts of String(preceding,exceding). Added the replace String inbetween these parts to generate final return String.

Following function allows to use any Character.
where as RegExp will not allow some special Character like ** and some Character need to be escape like $.

String.prototype.replaceAllMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
    var retStr = this;
    for (var x in obj) {
        //var matchArray = retStr.match(new RegExp(x, 'ig'));
        //for (var i = 0; i < matchArray.length; i++) {
        var prevIndex = retStr.indexOf(x); // matchkey = '*', replaceStr = '$*' While loop never ends.
        while (retStr.includes(x)) {
            retStr = retStr.replaceMatch(x, obj[x], 0);
            var replaceIndex = retStr.indexOf(x);
            if( replaceIndex <  prevIndex + (obj[x]).length) {
            } else {
                prevIndex = replaceIndex;
    return retStr;
String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
    var retStr = this, repeatedIndex = 0;
    //var matchArray = retStr.match(new RegExp(matchkey, 'ig'));
    //for (var x = 0; x < matchArray.length; x++) {
    for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
        if (repeatedIndex == 0 && x == 0) {
            repeatedIndex = retStr.indexOf(matchkey);
        } else { // matchIndex > 0
            repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
        if (x == matchIndex) {
            retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
            matchkey = null; // To break the loop.
    return retStr;

We can also use regular expression object for matching text with a pattern. The following are functions which will regular expression object.

You will get SyntaxError when you are using Invalid regular expression patter like '**'.

  • String.replace() function is used to replace the specified String with the given String.
  • String.match() function is to find how many time the String is repeated.
  • RegExp.prototype.test method executes a search for a match between a regular expression and a specified string. Returns true or false.
String.prototype.replaceAllRegexMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
    var retStr = this;
    for (var x in obj) {
        retStr = retStr.replace(new RegExp(x, 'ig'), obj[x]);
    return retStr;

Note that regular expressions are written without quotes.

Examples to use above funtions:

var str = "yash yas $dfdas.**";
console.log('String : ', str);

// No need to escape any special Character
console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );
console.log('All Matched replace : ', str.replaceAllMatches({'as' : '**', 'y':'Y', '$':'-'}));
console.log('All Matched replace : ', str.replaceAllMatches({'**' : '~~', '$':'&$&', '&':'%', '~':'>'}));

// You need to escape some special Characters
console.log('REGEX All Matched replace : ', str.replaceAllRegexMatches({'as' : '**', 'y':'Y', '\\$':'-'}));


String :  yash yas $dfdas.**
Index Matched replace :  yash yas $dfd*.**
Index Matched replace :  yash ~as $dfdas.**

All Matched replace :  Y**h Y** -dfd**.**
All Matched replace :  yash yas %$%dfdas.>>

REGEX All Matched replace :  Y**h Y** -dfd**.**

@ashish 2019-01-29 05:05:24

Method 1

Try to implement regular expression

"Test abc test test abc test test test abc test test abc".replace(/\abc/g,' ');

Method 2

Split And join. Split with abc and join with empty space

"Test abc test test abc test test test abc test test abc".split("abc").join(" ")

@Arian saputra 2019-01-22 12:33:37

you can try like this:

example data:

var text = "heloo,hai,hei"

text = text.replace(/[,]+/g,'')


  hasil = hasil.replace(',','')

@wiktus239 2019-01-22 12:44:09

This question is over 9 years old. Your answer doesn't contribute more than what has already been answered. I'm sorry but this irrelevant now.

@Sandeep Gantait 2016-02-16 09:53:06

The following function works for me:

String.prototype.replaceAllOccurence = function(str1, str2, ignore)
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;

Now call the functions like this:

"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");

Simply copy and paste this code in your browser console to TEST.

@Andrés 2018-01-26 23:05:35

I just want to share my solution, based on some of the functional features of last versions of JavaScript:

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

   var result = str.split(' ').reduce((a, b) => {
      return b == 'abc' ? a : a + ' ' + b;   })


@Black 2018-10-23 09:34:02

The previous answers are way too complicated. Just use the replace function like this:

str.replace(/your_regex_pattern/g, replacement_string);


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

var res = str.replace(/[abc]+/g, "");


@Daniel Williams 2018-12-28 22:26:06

OMG thank you! This is the simplest and best answer.

@Ferie 2018-09-04 16:24:03

In terms of performance related to the main answers these are some online tests.

While the following are some performance tests using console.time() (they work best in your own console, the time is very short to be seen in the snippet)

console.time('split and join');
"javascript-test-find-and-replace-all".split('-').join(' ');
console.timeEnd('split and join')

console.time('regular expression');
"javascript-test-find-and-replace-all".replace(new RegExp('-', 'g'), ' ');
console.timeEnd('regular expression');

let str1 = "javascript-test-find-and-replace-all";
while (str1.indexOf('-') !== -1) {
    str1 = str1.replace('-', ' ');

The interesting thing to notice is that if you run them multiple time the results are always different even though the RegExp solution seems the fastest on average and the while loop solution the slowest.

@rakslice 2013-06-19 23:21:09

If what you want to find is already in a string, and you don't have a regex escaper handy, you can use join/split:

    function replaceMulti(haystack, needle, replacement)
        return haystack.split(needle).join(replacement);

    someString = 'the cat looks like a cat';
    console.log(replaceMulti(someString, 'cat', 'dog'));

@mostafa elmadany 2017-10-07 20:56:16

If the string contain similar pattern like abccc, you can use this:

str.replace(/abc(\s|$)/g, "")

@TheAivis 2018-04-11 12:16:24

For unique replaceable values

String.prototype.replaceAll = function(search_array, replacement_array) {
  var target = this;
  search_array.forEach(function(substr, index) {
    if (typeof replacement_array[index] != "undefined") {
      target = target.replace(new RegExp(substr, 'g'), replacement_array[index])
  return target;

//  Use:
var replacedString = "This topic commented on :year. Talking :question.".replaceAll([':year', ':question'], ['2018', 'How to replace all occurrences of a string in JavaScript']);

@rak007 2018-04-20 13:19:00

Your code doesn't work if words share the same letters. Example : var test = "Groups_4_Questions_0__Options_0_Wording".replaceAll([4, 0, 0], [100, 200, 300])

@TheAivis 2018-04-20 13:52:22

Not meant for it. Only for unique replaceable values.

@rak007 2018-04-20 13:53:03

this is useless then in most case

@csomakk 2017-12-28 12:27:42

str = str.replace(new RegExp("abc", 'g'), "");

worked better for me than the above answers. so new RegExp("abc", 'g') creates a RegExp what matches all occurence ('g' flag) of the text ("abc"). The second part is what gets replaced to, in your case empty string (""). str is the string, and we have to override it, as replace(...) just returns result, but not overrides. In some cases you might want to use that.

@yivi 2017-12-28 15:46:02

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

@csomakk 2017-12-29 17:54:34

Yeah, you're right. added. also edited it to answer the original question :)

@firstpostcommenter 2018-07-02 16:15:50

Note: g flag in regex means it is global flag which will match all occurrences

@KARTHIKEYAN.A 2017-12-28 09:44:51

In string first element search and replace

var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'
var i = str.replace('"[','[').replace(']"',']');
console.log(i,'//first element search and replace')

In string global search and replace

var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}]'
var j = str.replace(/\"\[/g,'[').replace(/\]\"/g,']');
console.log(j,'//global search and replace')

@Chris Rosete 2015-06-19 21:24:21

Replacing single quotes:

function JavaScriptEncode(text){
    text = text.replace(/'/g,'&apos;')
    // More encode here if required

    return text;

@Stefan Đorđević 2016-12-09 22:37:51

How can i change second line to replace strings? This doesn't work: text = text.replace('hey', 'hello'); Any idea?

@Chris Rosete 2016-12-12 13:56:01

Sure Stefan, here is the code... text = text.replace(/hey/g, 'hello');

@Paulo Buchsbaum 2017-08-16 20:57:47

In my apps, I use a custom function that is the most powerful for this purpose, and even wrapping the split/join solution in the simpler case, it is a little bit faster in Chrome 60and Firefox 54 (JSBEN.CH) than other solutions. My computer runs Windows 7 64 bits.

The advantage is that this custom function can handle many substitutions at the same time using strings or characters, which can be a shortcut for some applications.

Like a split/join above solution, the solution below has no problem with escape characters, differently than regular expression approach.

  function replaceAll(s,find,repl,caseOff,byChar){
  if (arguments.length<2)  return false; 
  var destDel = ! repl;       // if destDel delete all keys from target
  var isString = !! byChar;   // if byChar, replace set of characters 
  if (typeof find !==typeof repl && ! destDel)  return false; 
  if (isString  &&  (typeof find!=="string"))   return false; 

  if (! isString &&  (typeof find==="string"))  {
    return s.split(find).join(destDel?"":repl);

  if ((! isString)  &&  ( ! Array.isArray(find) ||
          ( ! Array.isArray(repl) && ! destDel)   ))  return false;

     // if destOne replace all strings/characters by just one element
  var destOne = destDel ? false : (repl.length===1);   

     // Generally source and destination should have the same size
  if (! destOne && ! destDel && find.length!==repl.length)  return false    

  var prox,sUp,findUp,i,done;   
  if (caseOff)  {    // case insensitive    
       // Working with uppercase keys and target 
    sUp = s.toUpperCase();   
    if (isString)
       findUp = find.toUpperCase()   
       findUp ={  return el.toUpperCase();});    

  } else  {         // case sensitive
     sUp = s;
     findUp =find.slice();  // clone array/string

  done = new Array(find.length);  // size: number of keys

  var pos = 0;       // initial position in target s
  var r = "";   // initial result
  var aux, winner;
  while (pos < s.length)  {       // Scanning the target
     prox  = Number.MAX_SAFE_INTEGER;
     winner = -1;  // no winner at start
     for (i=0;i<findUp.length;i++)   // find next occurence for each string
       if (done[i]!==-1) {    // key still alive
             // Never search for the word/char or is over?
         if (done[i]===null || done[i]<pos)  { 
           aux = sUp.indexOf(findUp[i],pos);
           done[i]=aux;  // Save the next occurrence
         } else
           aux = done[i]   // restore the position of last search
         if (aux<prox && aux!==-1) {   // if next occurrence is minimum
           winner = i;     // save it  
           prox = aux;
       }  // not done

      if (winner===-1) {   // No matches forward
         r += s.slice(pos);   
      } // no winner

      // found the character or string key in the target

      i = winner;  // restore the winner
      r += s.slice(pos,prox);   // update piece before the match

            // Append the replacement in target 
      if (! destDel) r += repl[ destOne?0:i ];  
      pos = prox + ( isString?1:findUp[i].length );       // go after match

  }  // loop
  return r;  // return the resulting string

The documentation is below

      replaceAll(s,find,[ repl ,caseOff, byChar)     


   "s" is a string target of replacement.    
   "find" can be a string or array of strings.     
   "repl" should be the same type than "find" or empty     

  if "find" is a string, it is a simple replacement for      
    all "find" occurrences in "s" by string "repl"    

  if "find" is an array, it will replaced each string in "find"    
    that occurs in "s" for corresponding string in "repl" array.
  The replace specs are independent: A replacement part cannot    
    be replaced again. 

  if "repl" is empty all "find" occurrences in "s" will be deleted.   
  if "repl" has only one character or element,    
      all occurrences in "s" will be replaced for that one.   

  "caseOff" is true if replacement is case insensitive     
       (default is FALSE)

  "byChar" is true when replacement is based on set of characters.    
  Default is false   

  if "byChar", it will be replaced in "s" all characters in "find"   
  set of characters for corresponding character in  "repl"
  set of characters   

  the function returns the new string after the replacement.  

To be fair, I ran the benchmark with no parameter test.

Here is my test set, using Node.js

function l() { return console.log.apply(null, arguments); }

var k=0;
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      ["ri","nea"],["do","fa"]));  //1
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      ["ri","nea"],["do"]));  //2
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      ["ri","nea"]));  //3
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
     "aeiou","","",true));  //4
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      "aeiou","a","",true));  //5
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      "aeiou","uoiea","",true));  //6
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      "aeiou","uoi","",true));  //7
l(++k,replaceAll("banana is a ripe fruit harvested near the river",
      ["ri","nea"],["do","fa","leg"]));  //8
      ["ri","nea"],["do","fa"]));  //9
      ["ri","nea"],["do","fa"],true)); //10

And the results:

1 'banana is a dope fruit harvested far the dover'
2 'banana is a dope fruit harvested dor the dover'
3 'banana is a pe fruit harvested r the ver'
4 'bnn s rp frt hrvstd nr th rvr'
5 'banana as a rapa fraat harvastad naar tha ravar'
6 'bununu is u ripo frait hurvostod nour tho rivor'
7 false
8 false

@Bart Read 2017-09-04 06:53:24

Downvoted because using this much code to achieve something so basic feels overkill to me.

@Paulo Buchsbaum 2017-09-05 18:34:34

It's matter of opinion. For me It's a powerhouse and fast function. I've used for years. One cannot do it on fewer lines. For those who just want to replace chars and pieces in strings without worrying about escape characters from regular expressions, it might be a good choice. The number of lines does not matter much, since it works is a tested black box

@Cole Lawrence 2014-04-04 18:49:46

This is the fastest version that doesn't use regular expressions.

Revised jsperf

replaceAll = function(string, omit, place, prevstring) {
  if (prevstring && string === prevstring)
    return string;
  prevstring = string.replace(omit, place);
  return replaceAll(prevstring, omit, place, string)

It is almost twice as fast as the split and join method.

As pointed out in a comment here, this will not work if your omit variable contains place, as in: replaceAll("string", "s", "ss"), because it will always be able to replace another occurrence of the word.

There is another jsperf with variants on my recursive replace that go even faster (!

  • Update July 27th 2017: It looks like RegExp now has the fastest performance in the recently released Chrome 59.

@Fr0zenFyr 2014-07-10 04:40:14

I loved your solution... I wish I could give you +10 but here's my +1. I think you can store index of the sub-string that was replaced and jump to the next if a match is found at a lower index to avoid that infinite loop problem. I can't comment about the performance because I didn't test it but that's just my 2 cents on this piece of excellence.

@Cole Lawrence 2014-07-10 12:41:44

@fr0zenfyr if you want to check if omit is in place (to prevent infinite loop) you could do a conditional like if(place.replace(omit) === omit) { No match, so it's safe to use replace loop } else { Match so use different method like split and join }

@Fr0zenFyr 2014-07-11 04:14:19

Hmm.. but whats the point combining two solutions? I'm anyway not a fan of split/join approach anyway.. thanks for the advise..

@Cole Lawrence 2014-07-11 13:13:19

@Fr0zenFyr I believe the purpose of combining the two solutions would be to fallback on a slower method if you can't use the faster one (when the loop would be infinite for example). So it would be a safe guard to ensure functionality with efficiency, but without possibility of failure.

@momomo 2017-07-07 09:52:19


@Sean Bright 2009-07-17 17:54:49

str = str.replace(/abc/g, '');

In response to comment:

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

In response to Click Upvote's comment, you could simplify it even more:

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);

Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the find function above without pre-processing it to escape those characters. This is covered in the Mozilla Developer Network's JavaScript Guide on Regular Expressions, where they present the following utility function:

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

So in order to make the replaceAll() function above safer, it could be modified to the following if you also include escapeRegExp:

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);

@Sean Bright 2009-07-17 19:47:19

Regular expressions are the only way to accomplish this "out of the box" without implementing your own 'replaceAll' method. I'm not suggesting their use just for the sake of using them.

@Click Upvote 2009-07-17 21:11:22

This is my own function from this comment: function replaceAll(find, replace,str) { var re = new RegExp(find, 'g'); str = str.replace(re, replace); return str; }

@Martin Ender 2013-08-27 00:39:25

Major caveat of of the replaceAll implementation is that it won't work if find contains metacharacters.

@Sean Bright 2013-08-27 10:20:09

Yes. You could couple it with the quote function from this answer to get around that.

@NET Experts 2013-09-16 10:30:41

This doesn't work for strings with $$. Example i have text variable $$Score. my text is "You got $$Score score.".

@Ifnot 2013-10-11 12:13:15

Inserting any string into RegExp is dangerous. For preventing unallowed char i protect find by using find = find.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); from…

@Jez 2014-09-10 13:35:57

Great answer. I used return string.replace(new RegExp(escapeRegExp(find), 'g'), replace); in my own ReplaceAll library function; shame JavaScript doesn't have this built-in.

@Kremena Lalova 2014-11-25 15:17:05

Can you explain why divText.replace(/[id]/g, shuttingDownId); replaced all my divs as well?

@jessiPP 2015-03-13 14:09:30

it should be noted that return string.replace(new RegExp(escapeRegExp(find), 'g'), replace); only works in firefox.

@Sean Bright 2015-03-13 14:20:55

@jessiPP: works for me in chrome -

@Onimusha 2015-07-01 22:42:06

Missing backslash error: return string.replace(/([.*+?^=!:${}()|\[\]\/\\\])/g, "\\$1"); (add ` before ])/g`)

@Sean Bright 2015-07-02 16:26:47

@Onimusha - There is no error. Can you point me to a jsfiddle that shows it not working?

@Onimusha 2015-07-02 16:38:10

@SeanBright you're right. I used your javascript in a php code so I had to add an extra backslash to escape. On the fiddle your code is perfect. I should have checked. Apologies

@Bennett 2017-03-12 20:12:51

Even simpler: String.prototype.replaceAll(find, replace) { return this.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), "g"), replace); } In practice: "abcdefgabcd323".replaceAll("abc", "1") // Returns "1defg1d323

@Emile Bergeron 2017-09-12 15:40:12

@SeanKPS 2017-09-28 14:27:41

if str = str.replace(/abc/g, ''); works, why use more code?

@Lankymart 2017-10-12 15:58:36

@SeanKPS actually read the answer and you'll find out why.

@Emilio Grisolía 2016-09-10 14:59:19

Say you want to replace all the 'abc' with 'x':

let some_str = 'abc def def lom abc abc def'.split('abc').join('x')
console.log(some_str) //x def def lom x x def

I was trying to think about something more simple than modifying the string prototype.

@machineghost 2016-10-25 23:51:29

Simple, easy, and probably the most performant option: nice answer.

@Emilio Grisolía 2017-01-13 18:18:11

I don't know if it performance-wise, but.... it works.

@machineghost 2017-01-13 18:30:07

Actually, while I haven't metric-ed it personally, split/join is usually a very performant solution.

@Olivier 2018-05-22 14:39:00

it's even in chrome, 100% faster on firefox, and 50% slower on IE...:

@SiwachGaurav 2013-12-24 11:05:33

For replacing all kind of characters, try this code:

Suppose we have need to send " and \ in my string, then we will convert it " to \" and \ to \\

So this method will solve this issue.

String.prototype.replaceAll = function (find, replace) {
     var str = this;
     return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);

var message = $('#message').val();
             message = message.replaceAll('\\', '\\\\'); /*it will replace \ to \\ */
             message = message.replaceAll('"', '\\"');   /*it will replace " to \\"*/

I was using Ajax, and I had the need to send parameters in JSON format. Then my method is looking like this:

 function sendMessage(source, messageID, toProfileID, userProfileID) {

     if (validateTextBox()) {
         var message = $('#message').val();
         message = message.replaceAll('\\', '\\\\');
         message = message.replaceAll('"', '\\"');
             type: "POST",
             async: "false",
             contentType: "application/json; charset=utf-8",
             url: "services/WebService1.asmx/SendMessage",
             data: '{"source":"' + source + '","messageID":"' + messageID + '","toProfileID":"' + toProfileID + '","userProfileID":"' + userProfileID + '","message":"' + message + '"}',
             dataType: "json",
             success: function (data) {
                 loadMessageAfterSend(toProfileID, userProfileID);
             error: function (result) {
                 alert("message sending failed");
     else {
         alert("Please type message in message box.");


 String.prototype.replaceAll = function (find, replace) {
     var str = this;
     return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);

@Owen 2013-05-15 14:03:03

I like this method (it looks a little cleaner):

text = text.replace(new RegExp("cat","g"), "dog"); 

@rakslice 2013-06-19 21:16:20

Okay, how do you escape the string to use it as a regex pattern?

@Donnie DeBoer 2009-07-17 17:56:03

Use a regular expression:

str.replace(/abc/g, '');

@Cory Gross 2013-07-12 01:46:24

For the sake of completeness, I got to thinking about which method I should use to do this. There are basically two ways to do this as suggested by the other answers on this page.

Note: In general, extending the built-in prototypes in JavaScript is generally not recommended. I am providing as extensions on the String prototype simply for purposes of illustration, showing different implementations of a hypothetical standard method on the String built-in prototype.

Regular Expression Based Implementation

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

Split and Join (Functional) Implementation

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

Not knowing too much about how regular expressions work behind the scenes in terms of efficiency, I tended to lean toward the split and join implementation in the past without thinking about performance. When I did wonder which was more efficient, and by what margin, I used it as an excuse to find out.

On my Chrome Windows 8 machine, the regular expression based implementation is the fastest, with the split and join implementation being 53% slower. Meaning the regular expressions are twice as fast for the lorem ipsum input I used.

Check out this benchmark running these two implementations against each other.

As noted in the comment below by @ThomasLeduc and others, there could be an issue with the regular expression-based implementation if search contains certain characters which are reserved as special characters in regular expressions. The implementation assumes that the caller will escape the string beforehand or will only pass strings that are without the characters in the table in Regular Expressions (MDN).

MDN also provides an implementation to escape our strings. It would be nice if this was also standardized as RegExp.escape(str), but alas, it does not exist:

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

We could call escapeRegExp within our String.prototype.replaceAll implementation, however, I'm not sure how much this will affect the performance (potentially even for strings for which the escape is not needed, like all alphanumeric strings).

@jonney 2013-07-24 15:18:13

May i ask what the g character is for when replacing all occurance of a string?

@Cory Gross 2013-07-25 00:06:07

It's an option for the regular expression engine to use when matching the expression. Specifically, the global option will match every instance of the given pattern. It can also be applied on the end of the expression like so: /(.{3})/g. The g modifier on the end of the previous expression corresponds to the same g used in my code.

@Vsevolod Golovanov 2014-03-24 13:24:09

@CoryGross, what's the point of var target = this;? Why not just return this.replace...?

@Cory Gross 2014-03-24 18:35:48

@this, There is no difference unless the person reading the code isn't 100% sure that this refers to the target string value in this case.

@andreszs 2015-01-19 00:01:14

On Android 4.1 the regexp method is 15% faster, but you are not escaping the expression to search for, so this benchmark is incomplete.

@Thomas Leduc 2016-02-17 16:09:35

There is an issue with this solution, if you're search string appears to contains special characters of a regexp expression, they will be interpreted. I recommend the @Sandy Unitedwolf answer.

@RobKohr 2016-02-21 01:12:56

The first one will do this: 'bla.bla'.replaceAll('.', '_'); "_______". The second one will do 'bla_bla', which is more generally what you want to do.

@Marcus 2016-03-03 10:10:37

Using the regex example to replace $ char will have interesting results ( replaceAll("$", "8", input) ) :)

@Elias Van Ootegem 2016-03-04 10:22:21

Pedantic, but often true: Don't augment the prototype of native types unless you really, really have to (ie never). Libraries have done so in the past, people have tried to make it work safely, and almost always ran into problems at some point.

@David Anderton 2016-03-31 10:09:26

I prefer not to fiddle with the String Prototype and just to call .replace(new RegExp(search, 'g'), replacement) on the string directly.

@Toastrackenigma 2016-05-04 21:47:40

It might be worth noting that in Chrome 50 on a Mac, the "split and join" method leaves commas where the replaced text was, meaning it probably doesn't work consistently across browsers / platforms. All the more reason to use RegEx.

@HoldOffHunger 2016-08-30 00:58:28

Gloss over answer. Go to the next, "incorrect"-marked answer with 5x more votes. That's what you want.

@mattnificent 2018-03-15 07:47:58

@ThomasLeduc it looks like the issue you mentioned can be worked around with lodash =>

@Ben Cooper 2018-04-06 19:28:51

Leaving this here for future viewers who are also wondering why extending the native object is a bad idea:…

@Teekin 2018-08-22 12:47:36

It is patently absurd that people have to implement this basic functionality themselves. Thanks for the great response.

@Ferie 2018-09-06 09:42:01

In terms of performance, please have a look at my answer here…

@dash1e 2018-09-06 15:01:59

Please remove the .split and .join sample!

@Andy 2018-10-06 05:22:45

It's kind of bizarre that JavaScript doesn't provide a simple and easy way to replace all occurrences of a string and that we have to resort to escaping regexp special characters. And also that I only ran into this after four years of writing JavaScript...

@Saeb Panahifar 2018-12-12 10:07:15

Thanks, It's very useful.

@CodeToad 2018-12-24 12:40:17

note that if you make the string much longer in the benchmark, split is faster than regex.

@lcjury 2019-01-25 20:25:43

I wouldnt recommend the Functional) Implementation. It's a nice solution, but, it make use of a strange behaviour to solve the problem. The expresion based solution is much straightforward.

@DoMiNeLa10 2019-01-27 13:03:44

In Firefox 64, the split and join method is faster by around 25%, at times by almost 40%, while Chromium 71 has the RegExp approach win by about 3%. Things have changed, adding which version of the browser you've tested would clear things up.

@User 2017-03-17 04:58:47

Most people are likely doing this to encode a URL. To encode a URL, you shouldn't only consider spaces, but convert the entire string properly with encodeURI.

encodeURI(" file with spaces.html")

to get:

@Termininja 2016-01-12 23:43:48

I use p to store the result from the previous recursion replacement:

function replaceAll(s, m, r, p) {
    return s === p || r.contains(m) ? s : replaceAll(s.replace(m, r), m, r, s);

It will replace all occurrences in the string s until it is possible:

replaceAll('abbbbb', 'ab', 'a') → 'abbbb' → 'abbb' → 'abb' → 'ab' → 'a'

To avoid infinite loop I check if the replacement r contains a match m:

replaceAll('abbbbb', 'a', 'ab') → 'abbbbb'

@Matthew Crumley 2009-07-17 20:29:12

Note: Don't use this in real code.

As an alternative to regular expressions for a simple literal string, you could use

str = "Test abc test test abc test...".split("abc").join("");

The general pattern is


This used to be faster in some cases than using replaceAll and a regular expression, but that doesn't seem to be the case anymore in modern browsers. So, this should really only be used as a quick hack to avoid needing to escape the regular expression, not in real code.

@MgSam 2013-09-20 20:22:39

It surprised me, as I would expect this method to be allocating more objects, creating more garbage, and thus take longer, but when I actually tested in a browser this method was consistently about 20% faster than the accepted response. Results may vary, of course.

@Matthew Crumley 2013-09-20 20:45:21

@MgSam Yes, JavaScript performance can definitely be unintuitive and inconsistent sometimes.

@fabi 2013-11-23 21:02:01

I was curious myself, and set up this: . It seems that v8 is just crazy fast at splitting/joining arrays compared to other javascript engines.

@tobriand 2014-04-03 08:01:15

Very nice - also saves you from the possibility of bad RegExps when passing in special characters. I'm adding in a generic flag for "find this and replace it" in an object property, but was concerned if I needed to replace "." or "}" and forgot I was using RegEx 3 months later!

@mrk 2014-05-30 03:30:09

On my ipad2/safari, split/join is 65% slower than replace so your results may vary.

@Fr0zenFyr 2014-07-09 03:41:26

@fabi when I test this on the jsperf you created, I get that replace() is over 75% faster than this approach. I understand the "results may vary" but the variation is huge..dont you think?

@Matthew Crumley 2014-07-09 19:53:04

@Fr0zenFyr I don't know if I've ever seen them that different in performance, but it depends a lot on what browser you're using. 'replace()' is faster in some and slower in others. The primary difference though is that 'split()/join()' lets you use a string without interpreting it as a regular expression, which is unfortunately the only (standard) way to do a global replace.

@MacroMan 2014-09-26 11:50:30

And as String.prototype: String.prototype.replaceAll = function(f,r){return this.split(f).join(r);}. Usage: "My string".replaceAll('st', ''); produces "My ring"

@sertsedat 2015-06-23 09:59:15

This is fantastic!! The regexp version is not working in my case because I want to replace a url which comes as and the slashes is stopping regexps.

@degr 2015-10-23 08:32:54

RegExp work more faster than split().join() on long strings. May be you can do it on small text, but I don't see any reasons to do that. Also, using regexp you have much more flexibility, like replace(/(ff)|(f)/g, '')

@corsiKa 2016-08-29 20:39:42

Am I the only one that thinks a factor of 2 or 3 isn't that big of a deal for something like this, which is probably not the critical part of your program?

@Matthew Crumley 2016-08-29 21:53:56

@corsiKa I definitely agree with that. The relative performance probably doesn't matter in 99% of cases, and probably varies depending on browser/environment and the specific strings you're dealing with anyway. In practice, I almost always use replace with a global regular expression, since that's what it's made for. The split/join trick is really only useful if the pattern can't be hard-coded and shouldn't be interpreted as a regular expression, and using new RegExp() after escaping special characters is arguably better (more clear, at the cost of some complexity).

@Hal50000 2016-10-02 18:27:03

@corsiKa Yes, Another shameful bit of JavaScripty. Only in the most trivial of Angular demos would this be an issue. Not using "replace" for replace is to replace replace with an absurd outlier. But then, absurd outliers are 99.99 percent of JavaScript programming.

@Pacerier 2017-01-24 02:35:37

@MgSam, This is faster because you don't have to use the regex engine. And regex is slow as snail.

@John R Perry 2017-02-10 21:20:16

Similar to Fr0zenFyr and mrk, I ran the test and replace was 35% faster.

@Worthy7 2017-03-02 05:06:19

split and join is 59% slower on my chrome...

@Steve Chambers 2017-04-21 12:57:51

Great answer! Out of interest, why do you advise not to use this in real code?

@Matthew Crumley 2017-05-01 18:12:58

@SteveChambers As far as hacks go, it's not the worst (in my opinion), but it's still a hack. In real code I would use the built-in replace method because it's more clear and faster in most cases.

@Steve Chambers 2017-05-01 21:08:20

@MatthewCrumley Thanks for the explanation. If it really is a hack it's one of the cleanest I've come across. When speed isn't an issue it's nice to be able to avoid literal escaping required when using a regex to do a job it's not necessarily always needed for - as for clarity, agreed but easily fixed by a simple comment to explain - with optional link to this SO answer :-)

@Alph.Dev 2017-05-06 13:51:24

May 2017 update: Split-Join is 3x-5x faster than anything else in Firefox, but 2x slower than anything else in Chrome.

@youen 2018-04-19 08:43:04

I don't see a reason for the warning to not use this in production. It's not more a hack than escaping a regex just because you want to replace multiple occurrences, but don't need a regex in the first place. Just wrap this so called "hack" in a nice replaceAll function, and it becomes just as readable as anything else. Since performance is not bad, there's no reason to avoid this solution.

@Bruce Pierson 2018-12-05 23:35:14

Incredibly, in Firefox this method is 25X (!) faster than the regex replace. 126.6 million ops/sec vs. 4.8 million.

@Nivesh Saharan 2016-03-04 08:11:27

Here is the working code with prototype:

String.prototype.replaceAll = function(find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);

@Antonio Mirarchi 2014-01-07 19:11:29

Try this:

String.prototype.replaceAll = function (sfind, sreplace) {
    var str = this;

    while (str.indexOf(sfind) > -1) {
        str = str.replace(sfind, sreplace);

    return str;

@Aamir Afridi 2014-10-09 09:59:42

@Jonatha ANTOINE 2016-06-24 08:43:08

if the replacement contains the "find" youi will have an infinite loop

@C. Morgan 2016-10-15 16:54:45

This can be solved using regular expressions and the flag g, which means to not stop after finding the first match. Really, regular expressions are life savers!

function replaceAll(string, pattern, replacement) {
    return string.replace(new RegExp(pattern, "g"), replacement);

// or if you want myString.replaceAll("abc", "");

String.prototype.replaceAll = function(pattern, replacement) {
    return this.replace(new RegExp(pattern, "g"), replacement);

Related Questions

Sponsored Content

43 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

76 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5513862 View
  • 6837 Score
  • 76 Answer
  • Tags:   javascript arrays

48 Answered Questions

80 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

26 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

31 Answered Questions

[SOLVED] For-each over an array in JavaScript?

22 Answered Questions

[SOLVED] How to check if a string contains a substring in Bash

  • 2008-10-23 12:37:31
  • davidsheldon
  • 1590625 View
  • 1973 Score
  • 22 Answer
  • Tags:   string bash substring

57 Answered Questions

[SOLVED] What is the difference between String and string in C#?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

39 Answered Questions

[SOLVED] Sort array of objects by string property value

Sponsored Content