How to replace all occurrences of a string in JavaScript?

Created 17.07.2009 17:53
Viewed 3.75M times
4792 votes

I have this string in my JavaScript code:

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

3
Comments
When replacing all occurrences of aba in ababa with ca, which result do you expect? caba? abca? cca? by reinierpost, 02.08.2019 12:58
String.prototype.replaceAll() is now a standard part of ECMAScript tc39.es/ecma262/#sec-string.prototype.replaceall, documented at developer.mozilla.org/docs/Web/JavaScript/Reference/… and shipped in Safari 13.1, Firefox 77 and Chrome Dev/Canary and will ship in Chrome 85. From the docs: “If searchValue is a string, replaces all occurrences of searchValue (as if .split(searchValue).join(replaceValue) or a global & properly-escaped regular expression had been used). If searchValue is a non-global regular expression, throws an exception” by sideshowbarker, 29.06.2020 05:26
Use regex instead of string, should look like str.replace(/abc/g, ''); so g to get all matches. by sarea, 29.07.2020 06:17
Answers 50
5
4662

As of August 2020

Modern browsers have support for the String.replaceAll() method defined by the ECMAScript 2021 language specification.

For older/legacy browser support:


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 (which has changed at least twice since this answer was originally written, so make sure to check the MDN site for potential updates):

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

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);
}
17.07.2009 17:54
Comments
when replace string using '/' , the RegeExp appraoche worked for me by Rahal Kanishka, 31.08.2020 06:04
Which version of Node JS do I need to use replaceAll? by Clifton Labrum, 16.10.2020 00:32
As of 12-2020 support for this is a mixed bag. The JS runtime on React Native for iOS support replaceAll(). The Android JS runtime doesn't. by David Vernon, 15.12.2020 20:14
This was the only solution which worked for me in Deno by hkong, 09.01.2021 01:54
What do you mean by greenfield browsers? by Mattia Rasulo, 15.03.2021 09:30
0
2462

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

12.07.2013 01:46
13
2085

Update: In the latest versions of most popular browsers, you can use replaceAll as shown here:

let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"

But check Can I use or another compatibility table first to make sure the browsers you're targeting have added support for it first.


For Node and compatibility with older/non-current browsers:

Note: Don't use the following solution in performance critical 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

str.split(search).join(replacement)

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.

Conclusion: If you have a performance critical use case (e.g processing hundreds of strings), use the Regexp method. But for most typical use cases, this is well worth not having to worry about special characters.

17.07.2009 20:29
Comments
Now from august 2020, you can use inbuilt replaceAll function, stackoverflow.com/a/63587267/8798220 by Nisharg Shah, 25.08.2020 21:22
Funny that they needed more than 20 years to add a function like replaceAll. by Remirror, 20.09.2020 12:57
I discourage from using replaceAll at this moment (2020). It is not supported by some browsers that had updates in this year caniuse.com/?search=replaceAll It is too early by Tomasz Smykowski, 19.10.2020 18:31
And replaceAll is NOT yet supported on NodeJS ! by Ananta K Roy, 25.11.2020 08:33
@NishargShah replaceAll isn't supported in IE. by Himel Nag Rana, 26.11.2020 04:24
yes I know, only modern browsers are supporting this by Nisharg Shah, 26.11.2020 07:44
ohh god, after I commented that comment, all high voted questions are edited by their users by Nisharg Shah, 26.11.2020 07:58
Node does not support this. by TemporaryFix, 03.12.2020 21:51
right i looked at this answer and wanted to say its not supported either by Ahmad, 29.12.2020 00:10
NodeJS supports replaceAll in 15.x versions. by Abion47, 25.02.2021 01:38
replaceAll not supported on Chromium-Edge mobile version 46.01. by Mr. Cooper, 08.03.2021 20:35
Just polifyll replaceAll with Babel! Is someone still not using that in 2021 after all? by Mattia Rasulo, 15.03.2021 09:28
Many are looking for converting a .json into .jsonl please refer this stackoverflow.com/a/62107172/3152654 by imsheth, 22.04.2021 03:47
Show remaining 8 comments
0
736

Using a regular expression with the g flag set will replace all:

someString = 'the cat looks like a cat';
anotherString = someString.replace(/cat/g, 'dog');
// anotherString now contains "the dog looks like a dog"

See here also

06.05.2009 23:18
0
118

Here's a string prototype function based on the accepted answer:

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find, 'g'), replace);
};

EDIT

If your find will contain special characters then you need to escape them:

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

Fiddle: http://jsfiddle.net/cdbzL/

11.02.2013 23:03
0
89

Update:

It's somewhat late for an update, but since I just stumbled on this question, and noticed that my previous answer is not one I'm happy with. Since the question involved replaceing a single word, it's incredible nobody thought of using word boundaries (\b)

'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"

This is a simple regex that avoids replacing parts of words in most cases. However, a dash - is still considered a word boundary. So conditionals can be used in this case to avoid replacing strings like cool-cat:

'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong
//"a dog is not a cool-dog" -- nips
'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');
//"a dog is not a cool-cat"

basically, this question is the same as the question here: Javascript replace " ' " with " '' "

@Mike, check the answer I gave there... regexp isn't the only way to replace multiple occurrences of a subsrting, far from it. Think flexible, think split!

var newText = "the cat looks like a cat".split('cat').join('dog');

Alternatively, to prevent replacing word parts -which the approved answer will do, too! You can get around this issue using regular expressions that are, I admit, somewhat more complex and as an upshot of that, a tad slower, too:

var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");

The output is the same as the accepted answer, however, using the /cat/g expression on this string:

var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');
//returns "the dog looks like a dog, not a dogerpillar or cooldog" ?? 

Oops indeed, this probably isn't what you want. What is, then? IMHO, a regex that only replaces 'cat' conditionally. (ie not part of a word), like so:

var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
//return "the dog looks like a dog, not a caterpillar or coolcat"

My guess is, this meets your needs. It's not fullproof, of course, but it should be enough to get you started. I'd recommend reading some more on these pages. This'll prove useful in perfecting this expression to meet your specific needs.

http://www.javascriptkit.com/jsref/regexp.shtml

http://www.regular-expressions.info


Final addition:

Given that this question still gets a lot of views, I thought I might add an example of .replace used with a callback function. In this case, it dramatically simplifies the expression and provides even more flexibility, like replacing with correct capitalisation or replacing both cat and cats in one go:

'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
   .replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
    {
       //check 1st, capitalize if required
       var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
       if (char1 === ' ' && char2 === 's')
       {//replace plurals, too
           cat = replacement + 's';
       }
       else
       {//do not replace if dashes are matched
           cat = char1 === '-' || char2 === '-' ? cat : replacement;
       }
       return char1 + cat + char2;//return replacement string
    });
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar
01.03.2012 10:02
0
72

Match against a global regular expression:

anotherString = someString.replace(/cat/g, 'dog');
06.05.2009 23:23
0
65

For replacing a single time use:

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

For replacing multiple times use:

var res = str.replace(/abc/g, "");
29.05.2019 11:11
0
62

These are the most common and readable methods.

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

Method 1:

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

Method 2:

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

Method 3:

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

Method 4:

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
25.03.2019 09:38
0
45
str = str.replace(/abc/g, '');

Or try the replaceAll method, as recommended in this answer:

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

or:

var search = 'abc';
str = str.replaceAll(search, '');

EDIT: Clarification about replaceAll availability

The replaceAll method is added to String's prototype. This means it will be available for all string objects/literals.

Example:

var output = "test this".replaceAll('this', 'that'); // output is 'test that'.
output = output.replaceAll('that', 'this'); // output is 'test this'
17.07.2009 17:55
0
43

Using RegExp in JavaScript could do the job for you, just simply do something like below code, 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.

06.06.2017 13:39
0
41

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.

10.09.2016 14:59
0
37

Use a regular expression:

str.replace(/abc/g, '');
17.07.2009 17:56
2
32

Replacing single quotes:

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

    return text;
}
19.06.2015 21:24
Comments
How can i change second line to replace strings? This doesn't work: text = text.replace('hey', 'hello'); Any idea? by Stefan Đorđević, 09.12.2016 22:37
Sure Stefan, here is the code... text = text.replace(/hey/g, 'hello'); by Chris Rosete, 12.12.2016 13:56
1
30

Performance

Today 27.12.2019 I perform tests on macOS v10.13.6 (High Sierra) for the chosen solutions.

Conclusions

  • The str.replace(/abc/g, ''); (C) is a good cross-browser fast solution for all strings.
  • Solutions based on split-join (A,B) or replace (C,D) are fast
  • Solutions based on while (E,F,G,H) are slow - usually ~4 times slower for small strings and about ~3000 times (!) slower for long strings
  • The recurrence solutions (RA,RB) are slow and do not work for long strings

I also create my own solution. It looks like currently it is the shortest one which does the question job:

str.split`abc`.join``

str = "Test abc test test abc test test test abc test test abc";
str = str.split`abc`.join``

console.log(str);

Details

The tests were performed on Chrome 79.0, Safari 13.0.4 and Firefox 71.0 (64 bit). The tests RA and RB use recursion. Results

Enter image description here

Short string - 55 characters

You can run tests on your machine HERE. Results for Chrome:

Enter image description here

Long string: 275 000 characters

The recursive solutions RA and RB gives

RangeError: Maximum call stack size exceeded

For 1M characters they even break Chrome

enter image description here

I try to perform tests for 1M characters for other solutions, but E,F,G,H takes so much time that browser ask me to break script so I shrink test string to 275K characters. You can run tests on your machine HERE. Results for Chrome

enter image description here

Code used in tests

var t="Test abc test test abc test test test abc test test abc"; // .repeat(5000)
var log = (version,result) => console.log(`${version}: ${result}`);


function A(str) {
  return str.split('abc').join('');
}

function B(str) {
  return str.split`abc`.join``; // my proposition
}


function C(str) {
  return str.replace(/abc/g, '');
}

function D(str) {
  return str.replace(new RegExp("abc", "g"), '');
}

function E(str) {
  while (str.indexOf('abc') !== -1) { str = str.replace('abc', ''); }
  return str;
}

function F(str) {
  while (str.indexOf('abc') !== -1) { str = str.replace(/abc/, ''); }
  return str;
}

function G(str) {
  while(str.includes("abc")) { str = str.replace('abc', ''); }
  return str;
}

// src: https://stackoverflow.com/a/56989553/860099
function H(str)
{
    let i = -1
    let find = 'abc';
    let newToken = '';

    if (!str)
    {
        if ((str == null) && (find == null)) return newToken;
        return str;
    }

    while ((
        i = str.indexOf(
            find, i >= 0 ? i + newToken.length : 0
        )) !== -1
    )
    {
        str = str.substring(0, i) +
            newToken +
            str.substring(i + find.length);
    }
    return str;
}

// src: https://stackoverflow.com/a/22870785/860099
function RA(string, prevstring) {
  var omit = 'abc';
  var place = '';
  if (prevstring && string === prevstring)
    return string;
  prevstring = string.replace(omit, place);
  return RA(prevstring, string)
}

// src: https://stackoverflow.com/a/26107132/860099
function RB(str) {
  var find = 'abc';
  var replace = '';
  var i = str.indexOf(find);
  if (i > -1){
    str = str.replace(find, replace);
    i = i + replace.length;
    var st2 = str.substring(i);
    if(st2.indexOf(find) > -1){
      str = str.substring(0,i) + RB(st2, find, replace);
    }
  }
  return str;
}




log('A ', A(t));
log('B ', B(t));
log('C ', C(t));
log('D ', D(t));
log('E ', E(t));
log('F ', F(t));
log('G ', G(t));
log('H ', H(t));
log('RA', RA(t)); // use reccurence
log('RB', RB(t)); // use reccurence
<p style="color:red">This snippet only presents codes used in tests. It not perform test itself!<p>

27.12.2019 16:03
Comments
Now this is one hell of an in depth answer! Thank you very much! Although, what I'm curious about is why the "new RegExp(...)" syntax gives that much of an improvement. by Márk Gergely Dolinka, 31.12.2019 12:59
2
26

Loop it until number occurrences comes to 0, like this:

function replaceAll(find, replace, str) {
    while (str.indexOf(find) > -1) {
        str = str.replace(find, replace);
    }
    return str;
}
05.06.2013 04:57
Comments
This method is dangerous, do not use it. If the replacement string contains the search keyword, then an infinite loop will occur. At the very least, store the result of .indexOf in a variable, and use this variable as the second parameter of .indexOf (minus length of keyword, plus length of replacement string). by Rob W, 29.10.2013 11:33
I'm thinking about first replacing the search pattern with a weired unicode char, of that we are sure it is not used in the input string. Like U+E000 in the private area. And then replace it back to the target. I've build that here.. I'm not sure if thats a good Idea. by Lux, 02.07.2014 13:42
3
27
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.

28.12.2017 12:27
Comments
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. by yivi, 28.12.2017 15:46
Yeah, you're right. added. also edited it to answer the original question :) by csomakk, 29.12.2017 17:54
Note: g flag in regex means it is global flag which will match all occurrences by firstpostcommenter, 02.07.2018 16:15
6
25

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.
04.04.2014 18:49
Comments
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. by Fr0zenFyr, 10.07.2014 04:40
@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 } by Cole Lawrence, 10.07.2014 12:41
Hmm.. but whats the point combining two solutions? I'm anyway not a fan of split/join approach anyway.. thanks for the advise.. by Fr0zenFyr, 11.07.2014 04:14
@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. by Cole Lawrence, 11.07.2014 13:13
@momomo how flawed? by SandRock, 08.08.2019 12:11
@SandRock I don't remember, but the submitter even says there is a case where it won't work. It also just by looking at it looks flawed, namely it recursively replaces, instead of continuing from last found location, it seems to starts over. code totally impossible to understand as well. i can write better in two seconds also. by mmm, 09.08.2019 18:15
Show remaining 1 comments
0
21

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

19.06.2013 23:21
1
19
function replaceAll(str, find, replace) {
  var i = str.indexOf(find);
  if (i > -1){
    str = str.replace(find, replace); 
    i = i + replace.length;
    var st2 = str.substring(i);
    if(st2.indexOf(find) > -1){
      str = str.substring(0,i) + replaceAll(st2, find, replace);
    }       
  }
  return str;
}
29.09.2014 19:12
Comments
I wonder how well that performs ... substring is native or walks over char array to create the new characters. by mmm, 07.07.2017 09:53
2
16

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

text = text.replace(new RegExp("cat","g"), "dog"); 
15.05.2013 14:03
Comments
Okay, how do you escape the string to use it as a regex pattern? by rakslice, 19.06.2013 21:16
I dont, I just use it for plain text by Owen, 19.03.2019 11:58
0
13
while (str.indexOf('abc') !== -1)
{
    str = str.replace('abc', '');
}
29.04.2014 10:25
0
15

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

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

14.05.2019 18:42
0
12

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

23.10.2018 09:34
0
13

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

str.replace(/abc(\s|$)/g, "")
07.10.2017 20:56
1
12

As of August 2020 there is a Stage 4 proposal to ECMAScript that adds the replaceAll method to String.

It's now supported in Chrome 85+, Edge 85+, Firefox 77+, Safari 13.1+.

The usage is the same as the replace method:

String.prototype.replaceAll(searchValue, replaceValue)

Here's an example usage:

'Test abc test test abc test.'.replaceAll('abc', 'foo'); // -> 'Test foo test test foo test.'

It's supported in most modern browsers, but there exist polyfills:

It is supported in the V8 engine behind an experimental flag --harmony-string-replaceall. Read more on the V8 website.

11.11.2019 07:25
Comments
According to MDN, this has been available since Firefox 77 and Chromium 85. by pcworld, 03.06.2020 00:31
1
13
var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);

http://jsfiddle.net/ANHR9/

04.09.2013 10:01
Comments
what was the point of a fiddle that only contains the same javascript by JGallardo, 08.02.2017 00:42
0
10

If you are trying to ensure that the string you are looking for won't exist even after the replacement, you need to use a loop.

For example:

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

When complete, you will still have 'test abc'!

The simplest loop to solve this would be:

var str = 'test aabcbc';
while (str != str.replace(/abc/g, '')){
   str.replace(/abc/g, '');
}

But that runs the replacement twice for each cycle. Perhaps (at risk of being voted down) that can be combined for a slightly more efficient but less readable form:

var str = 'test aabcbc';
while (str != (str = str.replace(/abc/g, ''))){}
// alert(str); alerts 'test '!

This can be particularly useful when looking for duplicate strings.
For example, if we have 'a,,,b' and we wish to remove all duplicate commas.
[In that case, one could do .replace(/,+/g,','), but at some point the regex gets complex and slow enough to loop instead.]

28.09.2014 19:58
1
10

Although people have mentioned the use of regex but there's a better approach if you want to replace the text irrespective of the case of the text. Like uppercase or lowercase. Use below syntax

//Consider below example
originalString.replace(/stringToBeReplaced/gi, '');

//Output will be all the occurrences removed irrespective of casing.

You can refer the detailed example here.

03.05.2016 18:39
Comments
from the example site: "/toBeReplacedString/gi is the regex you need to use. Here g represents for global match and i represents case insensitive. By default regex is case sensitive" by alikuli, 03.08.2016 10:15
3
5

My implementation, very self explanatory

function replaceAll(string, token, newtoken) {
    if(token!=newtoken)
    while(string.indexOf(token) > -1) {
        string = string.replace(token, newtoken);
    }
    return string;
}
28.10.2011 02:36
Comments
This is incorrect. replaceAll("123434", "1234", "12") should return "1234" but instead returns "12". by Bryan, 16.04.2013 13:58
it depends if you allow to replace "recursively" or not. by Vitim.us, 16.04.2013 16:16
replaceAll("abc", "a", "ab") never terminates by user1002973, 16.05.2013 14:44
0
8

Just add /g

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

to

// Replace 'hello' string with /hello/g regular expression.
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

/g means global

05.06.2015 07:16
0
7

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.

16.02.2016 09:53
0
5

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);
 };
24.12.2013 11:05
0
7

You can simply use below method

/**
 * Replace all the occerencess of $find by $replace in $originalString
 * @param  {originalString} input - Raw string.
 * @param  {find} input - Target key word or regex that need to be replaced.
 * @param  {replace} input - Replacement key word
 * @return {String}       Output string
 */
function replaceAll(originalString, find, replace) {
  return originalString.replace(new RegExp(find, 'g'), replace);
};
15.02.2016 12:05
0
7

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 "
30.05.2019 04:43
0
6

Method 1

Try to implement a 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(" ")

29.01.2019 05:05
2
5

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'

16.08.2017 20:57
Comments
Downvoted because using this much code to achieve something so basic feels overkill to me. by Bart Read, 04.09.2017 06:53
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 by Paulo Buchsbaum, 05.09.2017 18:34
0
6

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'
12.01.2016 23:43
0
5

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("http://www.google.com/a file with spaces.html")

to get:

http://www.google.com/a%20file%20with%20spaces.html
17.03.2017 04:58
0
6

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;
}
16.04.2019 00:37
0
6

This can be achieved using regular expressions. A 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?]
15.02.2019 19:15
1
4
function replaceAll(str, find, replace) {
    var $r="";
    while($r!=str){ 
        $r = str;
        str = str.replace(find, replace);
    }
    return str;
}
11.04.2016 18:01
Comments
if the replacement contains the "find" youi will have an infinite loop by Jonathan ANTOINE, 24.06.2016 08:44
0
5

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.

04.09.2018 16:24
0
4

There is now a finished proposal for integrating String.prototype.replaceAll into the official specification. Eventually, developers will not have to come up with their own implementations for replaceAll - instead, modern Javascript engines will support it natively.

The proposal is at stage 4, which means that everything is complete, and all that's left is for browsers to start implementing it.

It has shipped in the latest versions of Chrome, Firefox, and Safari.

Here are the implementation details:

Per the current TC39 consensus, String.prototype.replaceAll behaves identically to String.prototype.replace in all cases, except for the following two cases:

  1. If searchValue is a string, String.prototype.replace only replaces a single occurrence of the searchValue, whereas String.prototype.replaceAll replaces all occurrences of the searchValue (as if .split(searchValue).join(replaceValue) or a global & properly-escaped regular expression had been used).
  2. If searchValue is a non-global regular expression, String.prototype.replace replaces a single match, whereas String.prototype.replaceAll throws an exception. This is done to avoid the inherent confusion between the lack of a global flag (which implies "do NOT replace all") and the name of the method being called (which strongly suggests "replace all").

Notably, String.prototype.replaceAll behaves just like String.prototype.replace if searchValue is a global regular expression.

You can see a spec-compliant polyfill here.

In supported environments, the following snippet will log foo-bar-baz, without throwing an error:

const str = 'foo bar baz';
console.log(
  str.replaceAll(' ', '-')
);

18.10.2019 02:48
3
4

Here's very simple solution. You can assign a new method to String object

String.prototype.replaceAll = function(search, replace){
   return this.replace(new RegExp(search, 'g'), replace)
}

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

console.log(str) // -> Test  test test  test test test  test test
22.06.2020 06:30
Comments
Assigning to the prototype of a global object is called prototype population and considered a pretty bad anti pattern. It is only acceptable for polyfills that implement the specified behavior of a function for old engines that don't support it yet. This implementation has different semantics than the spec. Consider 'hi'.replaceAll('.', 'x') // => 'xx' by Moritz, 28.07.2020 15:16
Thanks Moritz I think extending or modification of the prototypes of any objects, especially native ones is consider bad practice, but not to add new method If you have any source Please share by Iftikhar Hussain, 29.07.2020 16:38
Extending and "adding new methods" seems like the same thing to me. This is a problem because now there actually is a replaceAll method in the spec and it has different semantics which might break code, even in external dependencies. See: flaviocopes.com/javascript-why-not-modify-object-prototype by Moritz, 30.07.2020 17:24
0
3

If using a library is an option for you then you will get the benefits of the testing and community support that goes with a library function. For example, the string.js library has a replaceAll() function that does what you're looking for:

// Include a reference to the string.js library and call it (for example) S.
str = S(str).replaceAll('abc', '').s;
14.09.2014 18:12
0
0

You can try like this:

Example data:

var text = "heloo,hai,hei"

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

or

text.forEach((value) => {
  hasil = hasil.replace(',', '')
})
22.01.2019 12:33
2
1

Try this:

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

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

    return str;
};
07.01.2014 19:11
Comments
Don’t modify objects you don’t own by Aamir Afridi, 09.10.2014 09:59
if the replacement contains the "find" youi will have an infinite loop by Jonathan ANTOINE, 24.06.2016 08:43
0
4

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);
};
04.03.2016 08:11
3
3

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

11.04.2018 12:16
Comments
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]) by rak007, 20.04.2018 13:19
Not meant for it. Only for unique replaceable values. by TheAivis, 20.04.2018 13:52
this is useless then in most case by rak007, 20.04.2018 13:53