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"

Doing

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?

30 comments

@Raghavendra S 2019-05-30 04:43:39

Check this answer may it will help and I used in my project.

function replaceAll(searchString, replaceString, str) {
   return str.split(searchString).join(replaceString);
}
replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test  test test  test test test  test test "

@Indrajeet Singh 2019-05-29 11:11:11

For replacing a single time use:

var res = str.replace('abc', "");

For replacing multiple times use:

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

@Nouman Dilshad 2019-05-20 09:18:25

All the answers are accepted, you can do this by many ways. One of the trick to do this is this.

const str = "Test abc test test abc test test test abc test test abc";

const compare = "abc";
arrayStr = str.split(" ");
arrayStr.forEach((element, index) => {
  if (element == compare) {
    arrayStr.splice(index, 1);
  }
});
const newString = arrayStr.join(" ");
console.log(newString);

@sajadre 2019-05-14 18:42:20

The simplest way to this without using any regex is split and join like code here :

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

@jessie tessie 2019-05-09 05:11:44

This should work.

String.prototype.replaceAll = function (search, replacement){
var str1 = this.replace(search, replacement);
var str2 = this;
while(str1 != str2){
str2 = str1;
str1 = str1.replace(search, replacement);
}
return str1;
}

Example:

Console.log("Steve is the best character in minecraft".replaceAll("Steve" ,"Alex"));

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

Method-01:

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

Method-02:

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

Method-03:

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

Method-04:

while(str.includes("abc")){
    str = str.replace("abc", "replaced text");
}

Output:

console.log(str);
// 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 https://jsfiddle.net/pot6whnx/1/

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

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

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,

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

To replace question marks (?)

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

To replace quotation marks,

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

To replace all ' characters,

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

To replace a specific word,

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

To replace back-slash,

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

To replace forward slash,

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

To replace all spaces,

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

To replace dots,

console.log(word.replace(/\./g,'#')); 
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) {
                break;
            } 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', '\\$':'-'}));

Result:

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,'')

or

text.forEach(function(value){
  hasil = hasil.replace(',','')
})```

@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;   })

  console.warn(result)

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

Example:

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

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

console.log(res);

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

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

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']);
//
console.log(replacedString);

@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()   
    else
       findUp = find.map(function(el){  return el.toUpperCase();});    

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

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

  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);   
         break;
      } // 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    
 Syntax    
 ======     
      replaceAll(s,find,[ repl ,caseOff, byChar)     

 Parameters    
 ==========    

   "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   

 Return   
 ======   
  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
l(++k,replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
      ["ri","nea"],["do","fa"]));  //9
l(++k,replaceAll("BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER",
      ["ri","nea"],["do","fa"],true)); //10
return;

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
9 'BANANA IS A RIPE FRUIT HARVESTED NEAR THE RIVER'
10 'BANANA IS A doPE FRUIT HARVESTED faR THE doVER'

@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 (http://jsperf.com/replace-all-vs-split-join/12)!

  • 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

Flawed............

@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 stackoverflow.com/questions/3446170/…

@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 - jsfiddle.net/hrcbanto

@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 jsfiddle.net/7y19xyq8

@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...: jsperf.com/replace-regex-split-join

@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('"', '\\"');
         $.ajax({
             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);
                 $("#<%=PanelMessageDelete.ClientID%>").hide();
                 $("#message").val("");
                 $("#delMessageContainer").show();
                 $("#msgPanel").show();
             },
             error: function (result) {
                 alert("message sending failed");
             }
         });
     }
     else {
         alert("Please type message in message box.");
         $("#message").focus();

     }
 }

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

Related Questions

Sponsored Content

83 Answered Questions

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

79 Answered Questions

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

  • 2011-04-23 22:17:18
  • Walker
  • 5772038 View
  • 7203 Score
  • 79 Answer
  • Tags:   javascript arrays

61 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

22 Answered Questions

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

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

41 Answered Questions

[SOLVED] Sort array of objects by string property value

33 Answered Questions

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

26 Answered Questions

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

44 Answered Questions

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

Sponsored Content