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?


@VhsPiceros 2019-04-16 00:37:43

I use split and join or this funcion

function replaceAll( text, busca, reemplaza ){
  while (text.toString().indexOf(busca) != -1)
      text = text.toString().replace(busca,reemplaza);
  return text;

@Adnan Toky 2019-03-25 09:38:38

These are the most common and readable methods.

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


str = str.replace(/abc/g, "replaced text");


str = str.split("abc").join("replaced text");


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


    str = str.replace("abc", "replaced text");


// Test replaced text test test replaced text test test test replaced text test test replaced text

@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 use 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.

@Riajul Islam 2019-03-07 04:33:54

I have solved this problem by a simple line of code.

str.replace(/Current string/g, "Replaced string");

Check example on jsfiddle

@Rinold 2019-02-26 17:36:52

 var myName = 'r//i//n//o//l////d';
  var myValidName = myName.replace(new RegExp('\//', 'g'), ''); > // rinold

var myPetName = 'manidog';
var renameManiToJack = myPetName.replace(new RegExp('mani', 'g'), 'jack'); > // jackdog

@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, "");


@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

@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?

@Owen 2019-03-19 11:58:53

I dont, I just use it for plain text

@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...

@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.

@ninjaneer 2019-04-06 00:14:31

this solution didn't work for me.

@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'

Related Questions

Sponsored Content

3 Answered Questions

40 Answered Questions

[SOLVED] Sort array of objects by string property value

27 Answered Questions

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

59 Answered Questions

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

78 Answered Questions

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

  • 2011-04-23 22:17:18
  • Walker
  • 5655619 View
  • 7031 Score
  • 78 Answer
  • Tags:   javascript arrays

82 Answered Questions

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

33 Answered Questions

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

44 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

22 Answered Questions

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

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

Sponsored Content