5404

Given a string:

s = "Test abc test test abc test test test abc test test abc";

This seems to only remove the first occurrence of abc in the string above:

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

How do I replace all occurrences of it?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Ali
  • 261,656
  • 265
  • 575
  • 769
  • 19
    When replacing all occurrences of `aba` in `ababa` with `ca`, which result do you expect? `caba`? `abca`? `cca`? – reinierpost Aug 02 '19 at 12:58
  • 18
    `String.prototype.replaceAll()` is now a standard part of ECMAScript https://tc39.es/ecma262/#sec-string.prototype.replaceall, documented at https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll 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” – sideshowbarker Jun 29 '20 at 05:26
  • 19
    Use regex instead of string, should look like `str.replace(/abc/g, '');` so g to get all matches. – sarea Jul 29 '20 at 06:17

78 Answers78

5172

As of August 2020: Modern browsers have support for the String.replaceAll() method defined by the ECMAScript 2021 language specification.


For older/legacy browsers:

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

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

Here is how this answer evolved:

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

In response to comment "what's if 'abc' is passed as a variable?":

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);
}
izogfif
  • 6,000
  • 2
  • 35
  • 25
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
  • In `escapeRegExp` the `]` and `}` are extra (not necessary to be escaped). It is better to be like: `.replace(/[.^$*+?()[{|\\]/g, "\\$&")` – MMMahdy-PAPION Dec 30 '21 at 06:52
  • 1
    You also need to escape the replacement string (consider how `escapeRegExp` uses `$&` in the replacement string for special behavior). Change last `replace` in last code block to `replace.replace(/\$/g, '$$$$')`. See https://stackoverflow.com/a/6969486/2730641 Test case: `replaceAll('abc def abc', 'abc', '$&@%#!') // Censor 'abc'` – YipYip Jul 14 '22 at 23:01
  • @Sean Bright please read the comments https://stackoverflow.com/a/63587267/8798220 – Nisharg Shah Sep 26 '22 at 03:31
  • @NishargShah the first sentence of this answer references the `replaceAll()` method. – Sean Bright Sep 26 '22 at 13:36
  • Yes, I know, I am talking about the comments that this answer has, please check that. – Nisharg Shah Sep 28 '22 at 12:40
  • 1
    @NishargShah I do not remember what comments were on this answer 2 years ago but if you would like to edit this answer and credit yourself feel free. – Sean Bright Sep 28 '22 at 16:24
  • No need @SeanBright, I just want to inform you that, If you are seeing the code of someone and you liked it and you want to improve your answer based on that, then specifying that user name in your answer is good. – Nisharg Shah Sep 29 '22 at 09:16
2530

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cory Gross
  • 36,833
  • 17
  • 68
  • 80
  • In 2021 [String.prototype.replaceAll()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) natively exist. So this implementation should be checked first before use. – MMMahdy-PAPION Dec 26 '21 at 04:51
  • m using nestjs, so typescript showing error that replaceAll is not method of String prototype, any solution for this? – Sunil Garg Jan 05 '22 at 04:52
2366

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

Benchmark: https://jsben.ch/TZYzj

Conclusion:

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129
  • 18
    I discourage from using replaceAll at this moment (2020). It is not supported by some browsers that had updates in this year https://caniuse.com/?search=replaceAll It is too early – Tom Smykowski Oct 19 '20 at 18:31
  • 22
    NodeJS supports `replaceAll` in 15.x versions. – Abion47 Feb 25 '21 at 01:38
  • what to do in case-sensitive case – Kunal Tanwar Aug 27 '21 at 23:03
  • The benchmark's plain replace function is not the equivalent of regex /g. "If pattern is a string, only the first occurrence will be replaced. " EX: replaceAll_0("foo bar foo") => "bar foo" when it should just be "bar". -[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) – Tristan Forward Feb 12 '22 at 15:30
  • These solutions are way more readable than the reg-ex based solutions. Imo this should be the top answer. – fonzane Jun 21 '23 at 11:24
139

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

If your find contains 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/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jesal
  • 7,852
  • 6
  • 50
  • 56
101

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
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Adnan Toky
  • 1,756
  • 2
  • 11
  • 19
97

Use 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: Replace " ' " with " '' " in JavaScript

Regexp isn't the only way to replace multiple occurrences of a substring, 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 (i.e., 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 foolproof, 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.


Here is 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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
86

Match against a global regular expression:

anotherString = someString.replace(/cat/g, 'dog');
scronide
  • 12,012
  • 3
  • 28
  • 33
72

For replacing a single time, use:

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

For replacing multiple times, use:

var res = str.replace(/abc/g, "");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Indrajeet Singh
  • 2,958
  • 25
  • 25
60
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'
nik7
  • 806
  • 3
  • 12
  • 20
SolutionYogi
  • 31,807
  • 12
  • 70
  • 78
45

Using RegExp in JavaScript could do the job for you. Just simply do something like below code, and 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 affect some faster performance on long strings and is also a good practice of DRY code if you want to reuse.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alireza
  • 100,211
  • 27
  • 269
  • 172
43

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Emilio Grisolía
  • 1,183
  • 1
  • 9
  • 16
42

Use a regular expression:

str.replace(/abc/g, '');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Donnie DeBoer
  • 2,517
  • 15
  • 14
37

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>
Community
  • 1
  • 1
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 3
    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. – Márk Gergely Dolinka Dec 31 '19 at 12:59
34

Replacing single quotes:

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

    return text;
}
Termininja
  • 6,620
  • 12
  • 48
  • 49
Chris Rosete
  • 1,240
  • 15
  • 13
30

Using

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

worked better for me than the previous answers. So new RegExp("abc", 'g') creates a regular expression what matches all occurrences ('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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
csomakk
  • 5,369
  • 1
  • 29
  • 34
  • 1
    Warning! This method work well for just simple cases, but NEVER can be a main option. E.g., in case of any [RegExp Special Character](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#using_special_characters) ``.^$*+?()[{|\\`` exist in your string, can not return the expected result. – MMMahdy-PAPION Jan 15 '22 at 05:32
29

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;
}
nik7
  • 806
  • 3
  • 12
  • 20
Raseela
  • 315
  • 3
  • 2
  • 28
    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). – Rob W Oct 29 '13 at 11:33
28

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.
Cole Lawrence
  • 615
  • 6
  • 13
  • 1
    Re *"almost twice as fast"*: What was it tested on? Browser, JavaScript runtime, hardware, operating system, etc. All with versions and specifications (e.g. clock speed, CPU type, etc.). – Peter Mortensen Sep 24 '22 at 18:33
24

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'));
pitust
  • 99
  • 8
rakslice
  • 8,742
  • 4
  • 53
  • 57
21

String.prototype.replaceAll - ECMAScript 2021

The new String.prototype.replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be either a string or a RegExp, and the replacement can be either a string or a function to be called for each match.

const message = 'dog barks meow meow';
const messageFormatted = message.replaceAll('meow', 'woof')

console.log(messageFormatted);
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
  • 7
    `replaceAll` has already been suggested in almost 20 other answers and comments, including the accepted answer and the top-voted answer. What does this add? – Sebastian Simon Oct 16 '21 at 15:19
  • If you're looking for the method in Node.js, this will not work. https://replit.com/@RixTheTyrunt/rixxyplayer-parser?v=1 – RixTheTyrunt Mar 20 '22 at 15:38
  • 2
    @RixTheTyrunt Of course this will work in an up-to-date version of Node.js. – Sebastian Simon Mar 21 '22 at 08:30
  • @RixTheTyrunt No, it will work. Just make sure you set the `target` to `es2021` or above in `compilerOptions` inside the `tsconfig.json` file if you are using Typescript. – Beyondo Jul 31 '23 at 09:01
20
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;
}
Tim Rivoli
  • 208
  • 2
  • 5
18

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

text = text.replace(new RegExp("cat","g"), "dog"); 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Owen
  • 4,229
  • 5
  • 42
  • 50
17

Of course in 2021 the right answer is:

String.prototype.replaceAll()

console.log(
  'Change this and this for me'.replaceAll('this','that') // Normal case
);
console.log(
  'aaaaaa'.replaceAll('aa','a') // Challenged case
);

If you don't want to deal with replace() + RegExp.

But what if the browser is from before 2020?

In this case we need polyfill (forcing older browsers to support new features) (I think for a few years will be necessary). I could not find a completely right method in answers. So I suggest this function that will be defined as a polyfill.

My suggested options for replaceAll polyfill:

replaceAll polyfill (with global-flag error) (more principled version)
if (!String.prototype.replaceAll) { // Check if the native function not exist
    Object.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) String
        configurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)
        value: function(search, replace) { // Set the function by closest input names (For good info in consoles)
            return this.replace( // Using native String.prototype.replace()
                Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?
                    ? search.global // Is the RegEx global?
                        ? search // So pass it
                        : function(){throw new TypeError('replaceAll called with a non-global RegExp argument')}() // If not throw an error
                    : RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExp
                replace); // passing second argument
        }
    });
}
replaceAll polyfill (With handling global-flag missing by itself) (my first preference) - Why?
if (!String.prototype.replaceAll) { // Check if the native function not exist
    Object.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) String
        configurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)
        value: function(search, replace) { // Set the function by closest input names (For good info in consoles)
            return this.replace( // Using native String.prototype.replace()
                Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?
                    ? search.global // Is the RegEx global?
                        ? search // So pass it
                        : RegExp(search.source, /\/([a-z]*)$/.exec(search.toString())[1] + 'g') // If not, make a global clone from the RegEx
                    : RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExp
                replace); // passing second argument
        }
    });
}
Minified (my first preference):
if(!String.prototype.replaceAll){Object.defineProperty(String.prototype,'replaceAll',{configurable:!0,writable:!0,enumerable:!1,value:function(search,replace){return this.replace(Object.prototype.toString.call(search)==='[object RegExp]'?search.global?search:RegExp(search.source,/\/([a-z]*)$/.exec(search.toString())[1]+'g'):RegExp(String(search).replace(/[.^$*+?()[{|\\]/g,"\\$&"),"g"),replace)}})}
Try it:

if(!String.prototype.replaceAll){Object.defineProperty(String.prototype,'replaceAll',{configurable:!0,writable:!0,enumerable:!1,value:function(search,replace){return this.replace(Object.prototype.toString.call(search)==='[object RegExp]'?search.global?search:RegExp(search.source,/\/([a-z]*)$/.exec(search.toString())[1]+'g'):RegExp(String(search).replace(/[.^$*+?()[{|\\]/g,"\\$&"),"g"),replace)}})}

console.log(
  'Change this and this for me'.replaceAll('this','that')
); // Change that and that for me

console.log(
  'aaaaaa'.replaceAll('aa','a')
); // aaa

console.log(
  '{} (*) (*) (RegEx) (*) (\*) (\\*) [reserved characters]'.replaceAll('(*)','X')
); // {} X X (RegEx) X X (\*) [reserved characters]

console.log(
  'How (replace) (XX) with $1?'.replaceAll(/(xx)/gi,'$$1')
); // How (replace) ($1) with $1?

console.log(
  'Here is some numbers 1234567890 1000000 123123.'.replaceAll(/\d+/g,'***')
); // Here is some numbers *** *** *** and need to be replaced.

console.log(
  'Remove numbers under 233: 236   229  711   200   5'.replaceAll(/\d+/g, function(m) {
    return parseFloat(m) < 233 ? '' : m
  })
); // Remove numbers under 233: 236     711

console.log(
  'null'.replaceAll(null,'x')
); // x


// The difference between My first preference and the original:
// Now in 2022 with browsers > 2020 it should throw an error (But possible it be changed in future)

//   console.log(
//      'xyz ABC abc ABC abc xyz'.replaceAll(/abc/i,'')
//   );

// Browsers < 2020:
// xyz     xyz
// Browsers > 2020
// TypeError: String.prototype.replaceAll called with a non-global RegExp
Browser support:

The result is the same as the native replaceAll in case of the first argument input is: null, undefined, Object, Function, Date, ... , RegExp, Number, String, ...

Ref: 22.1.3.19 String.prototype.replaceAll ( searchValue, replaceValue) + RegExp Syntax

Important note: As some professionals mention it, many of recursive functions that suggested in answers, will return the wrong result. (Try them with the challenged case of the above snippet.) Maybe some tricky methods like .split('searchValue').join('replaceValue') or some well managed functions give same result, but definitely with much lower performance than native replaceAll() / polyfill replaceAll() / replace() + RegExp


Other methods of polyfill assignment

Naive, but supports even older browsers (be better to avoid)

For example, we can support IE7+ too, by not using Object.defineProperty() and using my old naive assignment method:

if (!String.prototype.replaceAll) {
    String.prototype.replaceAll = function(search, replace) { // <-- Naive method for assignment
        // ... (Polyfill code Here)
    }
}

And it should work well for basic uses on IE7+.
But as here @sebastian-simon explained about, that can make secondary problems in case of more advanced uses. E.g.:

for (var k in 'hi') console.log(k);
// 0
// 1
// replaceAll  <-- ?
Fully trustable, but heavy

In fact, my suggested option is a little optimistic. Like we trusted the environment (browser and Node.js), it is definitely for around 2012-2021. Also it is a standard/famous one, so it does not require any special consideration.

But there can be even older browsers or some unexpected problems, and polyfills still can support and solve more possible environment problems. So in case we need the maximum support that is possible, we can use polyfill libraries like:

https://polyfill.io/

Specially for replaceAll:

<script src="https://polyfill.io/v3/polyfill.min.js?features=String.prototype.replaceAll"></script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MMMahdy-PAPION
  • 915
  • 10
  • 15
15
while (str.indexOf('abc') !== -1)
{
    str = str.replace('abc', '');
}
zdennis
  • 185
  • 1
  • 2
15

The simplest way to do this without using any regular expression 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(''));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sajadre
  • 1,141
  • 2
  • 15
  • 30
14
var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);

http://jsfiddle.net/ANHR9/

pkdkk
  • 3,905
  • 8
  • 44
  • 69
14

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

str.replace(/abc(\s|$)/g, "")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
13

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.

Thomas Orlita
  • 1,554
  • 14
  • 28
  • [According to MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll), this has been available since Firefox 77 and Chromium 85. – pcworld Jun 03 '20 at 00:31
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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Black
  • 18,150
  • 39
  • 158
  • 271
12

After several trials and a lot of fails, I found that the below function seems to be the best all-rounder when it comes to browser compatibility and ease of use. This is the only working solution for older browsers that I found. (Yes, even though old browser are discouraged and outdated, some legacy applications still make heavy use of OLE browsers (such as old Visual Basic 6 applications or Excel .xlsm macros with forms.)

Anyway, here's the simple function.

function replaceAll(str, match, replacement){
   return str.split(match).join(replacement);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Oliver M Grech
  • 3,071
  • 1
  • 21
  • 36
  • 1
    This has already been suggested or mentioned in 18 other answers, and in the comments under the question. The compatibility considerations are easy to find on [CanIUse](//caniuse.com/?search=replaceAll) and [MDN](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll#browser_compatibility). This is all mentioned in the accepted answer. – Sebastian Simon Aug 30 '21 at 10:27
  • well at first glance I didn't find anything mentioning older browsers and OLE implementations in legacy code. Just thought it might help someone no point of downvoting a helpful answer. You don't have to upvote either I just care that someone might find it useful. Thanks for your contribution nevertheless – Oliver M Grech Aug 30 '21 at 12:42
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.]

SamGoody
  • 13,758
  • 9
  • 81
  • 91
10

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

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

// The output will be all the occurrences removed irrespective of casing.

You can refer to the detailed example here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cheezy Code
  • 1,685
  • 1
  • 14
  • 18
  • 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" – alikuli Aug 03 '16 at 10:15
9

With the regular expression i flag for case insensitive

console.log('App started'.replace(/a/g, '')) // Result: "App strted"
console.log('App started'.replace(/a/gi, '')) // Result: "pp strted"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
francis
  • 3,852
  • 1
  • 28
  • 30
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

Valentin Podkamennyi
  • 7,161
  • 4
  • 29
  • 44
Reza Fahmi
  • 270
  • 4
  • 11
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sandeep Gantait
  • 837
  • 8
  • 9
7

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 because the time is very short to be seen in the following 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 times, the results are always different even though the regular expression solution seems the fastest on average and the while loop solution the slowest.

Ferie
  • 1,358
  • 21
  • 36
7

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 backslash,

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?]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
prime
  • 14,464
  • 14
  • 99
  • 131
7

I use split and join or this function:

function replaceAll(text, busca, reemplaza) {
  while (text.toString().indexOf(busca) != -1)
    text = text.toString().replace(busca, reemplaza);
  return text;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
VhsPiceros
  • 410
  • 1
  • 8
  • 17
7

Check this answer. Maybe it will help, and I used it 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 "
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Raghavendra S
  • 513
  • 1
  • 5
  • 16
6

For replacing all kind of characters, try this code:

Suppose we have a 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);
 };
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SiwachGaurav
  • 1,918
  • 2
  • 17
  • 16
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'
Termininja
  • 6,620
  • 12
  • 48
  • 49
6

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);
};
tk_
  • 16,415
  • 8
  • 80
  • 90
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(" ")

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ashish
  • 2,026
  • 17
  • 19
6

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;
}
Vitim.us
  • 20,746
  • 15
  • 92
  • 109
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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
User
  • 23,729
  • 38
  • 124
  • 207
5

In my applications, 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 60 and 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 the above split/join solution, the solution below doesn't have any problems with escape characters, differently than the 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 the 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'

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paulo Buchsbaum
  • 2,471
  • 26
  • 29
  • 2
    Downvoted because using this much code to achieve something so basic feels overkill to me. – Bart Read Sep 04 '17 at 06:53
  • 1
    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 – Paulo Buchsbaum Sep 05 '17 at 18:34
  • I like how the function deal with array inputs, same as method of [str_replace](https://www.php.net/manual/en/function.str-replace.php) of PHP, but: 1. The function "caseOff" will not work while inputs be Strings. - 2. The benchmark absolutely and logically look not fair, When you define a function as prototype and redefine this and comment part of your code and also use just string inputs, the result is not fair. The fair can be this : https://jsben.ch/38Gj1 (Much different in results) – MMMahdy-PAPION Jan 20 '22 at 05:33
4

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;
Guy
  • 65,082
  • 97
  • 254
  • 325
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 specification-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(' ', '-')
);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
4

Here's a very simple solution. You can assign a new method to a 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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Iftikhar Hussain
  • 313
  • 3
  • 14
  • 1
    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' – Moritz Jul 28 '20 at 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 – Iftikhar Hussain Jul 29 '20 at 16:38
  • 2
    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: https://flaviocopes.com/javascript-why-not-modify-object-prototype/ – Moritz Jul 30 '20 at 17:24
3

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);
};
Termininja
  • 6,620
  • 12
  • 48
  • 49
Nivesh Saharan
  • 365
  • 3
  • 11
3
function replaceAll(str, find, replace) {
    var $r="";
    while($r!=str){ 
        $r = str;
        str = str.replace(find, replace);
    }
    return str;
}
theWalker
  • 2,022
  • 2
  • 18
  • 27
3

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')
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
  • The text is ***** ***incomprehensible*** *****: *"In string first element search and replace"* and *"In string global search and replace"*. Are you using [machine translation](https://en.wikipedia.org/wiki/Machine_translation) and/or are some words missing? Can you [fix it](https://stackoverflow.com/posts/48005111/edit)? – Peter Mortensen Sep 24 '22 at 18:58
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);
TheAivis
  • 181
  • 1
  • 4
3

In November 2019, a new feature is added to the JavaScript, string.prototype.replaceAll().

Currently it's only supported with Babel, but maybe in the future it can be implemented in all the browsers. For more information, read here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ace
  • 1,398
  • 13
  • 24
3

Use split and join:

var str = "Test abc test test abc test test test abc test test abc";
var replaced_str = str.split('abc').join('');
console.log(replaced_str);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Like many previous answers. What is different? – Peter Mortensen Sep 24 '22 at 20:21
  • Split and join is a great way to do `replaceAll` for two reasons: 1- Availability for `String.prototype.replaceAll` depends on the NodeJS version you're using. 2- If the searched value for replacement contains characters, using `replace` with regex global flag becomes harder. – zed Jan 02 '23 at 11:07
2

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

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

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

String.prototype.replaceAll = function(pattern, replacement) {
    return this.replace(new RegExp(pattern, "g"), replacement);
};
C. Morgan
  • 99
  • 1
  • 10
2

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andrés
  • 719
  • 1
  • 4
  • 21
2

The best solution, in order to replace any character we use the indexOf(), includes(), and substring() functions to replace the matched string with the provided string in the current string.

  • The String.indexOf() function is to find the nth match index position.
  • The 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). Add the replace String in-between these parts to generate final return String.

The following function allows to use any character.
where as RegExp will not allow some special character like ** and some characters need to be escaped, 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 the regular expression object for matching text with a pattern. The following are functions which will use the regular expression object.

You will get SyntaxError when you are using an invalid regular expression pattern like '**'.

  • The String.replace() function is used to replace the specified String with the given String.
  • The String.match() function is to find how many time the string is repeated.
  • The 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 the above functions:

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yash
  • 9,250
  • 2
  • 69
  • 74
  • In your loop you are repeatedly replacing in a string. This creates a new string on each iteration of the loop which for long strings will cost a lot of performance. Regex already have support to do all replaces in one go which is much faster as it will use tricks to avoid creating multiple new strings. – David Mårtensson May 20 '20 at 10:12
2
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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rinold
  • 343
  • 1
  • 2
  • 12
2

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"));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jessie Lesbian
  • 1,273
  • 10
  • 14
  • @aabbccsmith: In what way? Can you elaborate? – Peter Mortensen Mar 08 '20 at 18:26
  • The edit certainly cleared it up. Regardless, loops on strings like this shouldn't be endorsed as they are rather slow and could cause major lag on the main thread in large scale applications where this is ran multiple times per second. – alistair Mar 09 '20 at 13:13
  • " loops on strings like this shouldn't be endorsed " it would be good if that programming language wasn't so crappy – Luiz Felipe May 06 '20 at 16:49
2
str = "Test abc test test abc test test test abc test test abc"

str.split(' ').join().replace(/abc/g,'').replace(/,/g, ' ')
Das_Geek
  • 2,775
  • 7
  • 20
  • 26
Rakib Uddin
  • 880
  • 1
  • 6
  • 17
2

This solution combines some previous answers and conforms somewhat better to the proposed August 2020 standard solution. This solution is still viable for me in September 2020, as String.replaceAll is not available in the Node.js binary I am using.


RegExp.escape is a separate issue to deal with, but it is important here, because the official proposed solution will automatically escape string-based find input. This String.replaceAll polyfill would not without the RegExp.escape logic.

I have added an answer which doesn't polyfill RegExp.Escape, in the case that you don't want that.


If you pass a regular expression to find, you must include g as a flag. This polyfill won't provide a nice TypeError for you and will cause you a major bad time.

If you need exact standards conformance, for an application which is rigorously relying on the standard implementation, then I suggest using Babel or some other tool to get you the 'right answer' every time instead of Stack Overflow. That way you won't have any surprises.


Code:

if (!Object.prototype.hasOwnProperty.call(RegExp, 'escape')) {
  RegExp.escape = function(string) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
    // https://github.com/benjamingr/RegExp.escape/issues/37
    return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  };
}

if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
  String.prototype.replaceAll = function(find, replace) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
    // If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
    // TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
    // String parameters to 'find' do not require special handling.
    // Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
    // Does not conform to "Specifying a function as a parameter" for replace
    return this.replace(
          Object.prototype.toString.call(find) == '[object RegExp]' ?
            find :
            new RegExp(RegExp.escape(find), 'g'),
          replace
        );
  }
}

Code, Minified:

Object.prototype.hasOwnProperty.call(RegExp,"escape")||(RegExp.escape=function(e){return e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}),Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(RegExp.escape(e),"g"),t)});

Example:

console.log(
  't*.STVAL'
    .replaceAll(
      new RegExp(RegExp.escape('T*.ST'), 'ig'),
      'TEST'
    )
);

console.log(
  't*.STVAL'
    .replaceAll(
      't*.ST',
      'TEST'
    );
);

Code without RegExp.Escape:

if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
  String.prototype.replaceAll = function(find, replace) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
    // If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
    // TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
    // String parameters to 'find' do not require special handling.
    // Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
    // Does not conform to "Specifying a function as a parameter" for replace
    return this.replace(
          Object.prototype.toString.call(find) == '[object RegExp]' ?
            find :
            new RegExp(find.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'), 'g'),
          replace
        );
  }
}

Code without RegExp.Escape, Minified:

Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&"),"g"),t)});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Drewry Pope
  • 185
  • 3
  • 12
  • RegExp.Escape was based on my answer linked here: https://stackoverflow.com/a/63838890/5979634 – Drewry Pope Sep 13 '20 at 09:47
  • 1
    The `Object.prototype.hasOwnProperty.call(String, 'replaceAll')` will return **false** anyway, because it owned by `String.prototype` So it should be like: `Object.prototype.hasOwnProperty.call(String.prototype, 'replaceAll')` – MMMahdy-PAPION Jan 02 '22 at 03:52
  • MMMahdy-PAPION is right, but in addition it would be simpler and more transparent to simply check for `String.prototype.hasOwnProperty('replaceAll')` – Sebastian Mar 15 '23 at 13:08
2

JavaScript provides a direct way to replace a part of a string with another string and there are some tricks also by which you can do this.

To replace all the occurrences you can use replace() or replaceAll method in JavaScript.

  1. replace() method - To replace all elements using this method use a regular expression as a pattern to find the matching string and then replace it with a new string. Please consider using the /g flag with it.

const str = "To do or not to do";
const pattern = /do/g;
const replaceBy = "Code";
console.log(str.replace(pattern, replaceBy));
  1. replaceAll() method - To replace all elements using this method, use either a string or regular expression as a pattern to find the matching string and then replace it with a new string. We must use the /g flag with a regular expression in the replaceAll method.

const str = "To do or not to do";
const pattern = "do";
const replaceBy = "Code";
console.log(str.replaceAll(pattern, replaceBy));

const pattern2 = /do/g;
console.log(str.replaceAll(pattern2, replaceBy));

Alternate method: By using split and join method

Split the string at what you want to replace and join by using the new string as a separator. See the example.

const str = "To do or not to do";
const newStr = str.split("do").join("Code");
console.log(newStr);
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Satish Chandra Gupta
  • 2,970
  • 1
  • 22
  • 22
2

Repeat until you have replaced them all:

const regex = /^>.*/im;
while (regex.test(cadena)) {
    cadena = cadena.replace(regex, '*');
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pedro casas
  • 147
  • 5
  • This approach will replace occurrences which only appear after replacing. E.g. when replacing all occurrences of `"bc"` by `"b"`, then given the input string `"abcc"` should produce the output `"abc"`, but your approach will produce `"ab"`. – Sebastian Simon Sep 29 '21 at 10:17
  • This simple script, as Sebastian says, also removes the results that match the expression. This has its good and bad sides. The bad news has already been told by him. The good news is that it is very useful for removing JS tags in XSS and JavaScript Inject attacks. – pedro casas Sep 30 '21 at 11:15
1

Try this:

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

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

    return str;
};
C. Morgan
  • 99
  • 1
  • 10
1

The 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(" ")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

You can do it without Regex, but you need to be careful if the replacement text contains the search text.

e.g.

replaceAll("nihIaohi", "hI", "hIcIaO", true)

So here is a proper variant of replaceAll, including string-prototype:

function replaceAll(str, find, newToken, ignoreCase)
{
    let i = -1;

    if (!str)
    {
        // Instead of throwing, act as COALESCE if find == null/empty and str == null
        if ((str == null) && (find == null))
            return newToken;

        return str;
    }

    if (!find) // sanity check 
        return str;

    ignoreCase = ignoreCase || false;
    find = ignoreCase ? find.toLowerCase() : find;

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

    return str;
}

Or, if you want to have a string-prototype function:

String.prototype.replaceAll = function (find, replace) {
    let str = this;

    let i = -1;

    if (!str)
    {
        // Instead of throwing, act as COALESCE if find == null/empty and str == null
        if ((str == null) && (find == null))
            return newToken;

        return str;
    }

    if (!find) // sanity check 
        return str;

    ignoreCase = ignoreCase || false;
    find = ignoreCase ? find.toLowerCase() : find;

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

    return str;
};
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
1

In August 2020

No more regular expression stuff

const str = "Test abc test test abc test test test abc test test abc";
const modifiedStr = str.replaceAll('abc', '');
console.log(modifiedStr);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

Nisharg Shah
  • 16,638
  • 10
  • 62
  • 73
  • `Uncaught TypeError: str.replaceAll is not a function",` – raven Mar 12 '21 at 10:53
  • only the modern browser support it, if you are not using modern browsers then use `regex` – Nisharg Shah Mar 13 '21 at 03:28
  • This is already covered by at least one previous answer. – Peter Mortensen Sep 24 '22 at 20:23
  • @PeterMortensen Might be I was wrong but when I posted this answer, no one has this solution – Nisharg Shah Sep 26 '22 at 03:17
  • I just remembered, I left a comment of my answer on the top 3 answers of this question, and as a result that were removed, and the next day they edited the answer without acknowledging me. As proof, You can see the 14th Revision in the most upvoted answer https://stackoverflow.com/posts/1144788/revisions – Nisharg Shah Sep 26 '22 at 03:27
0

You can try like this:

Example data:

var text = "heloo,hai,hei"

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

or

text.forEach((value) => {
  hasil = hasil.replace(',', '')
})
Ran Marciano
  • 1,431
  • 5
  • 13
  • 30
Arian Saputra
  • 356
  • 6
  • 15
0

All the answers are accepted, and 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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nouman Dilshad
  • 1,014
  • 13
  • 16
0

We can use the replace method in JavaScript:

var result = yourString.replace('regexPattern', "replaceString");

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

var expectedString = str.replace(/abc(\s|$)/g, "");

console.log(expectedString);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lova Chittumuri
  • 2,994
  • 1
  • 30
  • 33
0

I know this isn’t the best way to do this, but you can try this:

var annoyingString = "Test abc test test abc test test test abc test test abc";

while (annoyingString.includes("abc")) {
    annoyingString = annoyingString.replace("abc", "")
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
e102
  • 85
  • 8
0

I added the function below to this performance test page in the "library" section:

https://jsben.ch/LFfWA

function _replace(t, s, r){
    var i = t.indexOf(s);
    if (i == -1) return t;
    return t.slice(0, i) + r + _replace(t.slice(i + s.length, t.length), s,r);
}

..and put this in as the test:

var replaced = _replace(testString, 'abc', '123');

.. and that function performs about 34% faster for me than split or regex. The idea / hope was to end up pasting smaller and smaller pieces of the string onto the stack and then building the entire result by unrolling the stack, thereby minimizing extra string copies and extra searches through the same string data and hopefully optimizing use of the CPU cache.

Part of the thought was that if the string isn't too big, it may end up in the CPU cache; passing it and pasting pieces of it puts those bits into the cache, and then the searching can operate entirely using CPU cached data. Now whether or not that's actually what ends up happening I'm sure is entirely JavaScript implementation-dependent.

This isn't as fast as possible, but it's as fast as I could manage without mutable strings. Arrays in JavaScript probably have a pointer for each element, so, a solution involving a lot of array elements is not likely to be as CPU cache friendly as this.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shavais
  • 2,476
  • 1
  • 27
  • 25
  • Re *"performs about 34% faster"*: What was it tested on? Browser, JavaScript runtime, hardware, operating system, etc. All with versions and specifications (e.g. clock speed, CPU type, etc.). – Peter Mortensen Sep 24 '22 at 20:12
0

Starting from v85, Chrome now supports String.prototype.replaceAll natively. Note this outperform all other proposed solutions and should be used once majorly supported.

Feature status: https://chromestatus.com/feature/6040389083463680

var s = "hello hello world";
s = s.replaceAll("hello", ""); // s is now "world"
console.log(s)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matěj Štágl
  • 870
  • 1
  • 9
  • 27
0

There is a way to use the new replaceAll() method.

But you need to use a cutting-edge browser or a JavaScript run time environment.

You can check the browser compatibility in here.

I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26
Chungmin Park
  • 21
  • 1
  • 1
  • 4
0
// Try this way

const str = "Test abc test test abc test test test abc test test abc";
const result = str.split('abc').join('');
console.log(result);
Force Bolt
  • 1,117
  • 9
  • 9
0

I have read this question and answers, but I didn't find an appropriate solution for me. Although the answers are quite useful, I decided to create my own solution from scratch. The problems about this kind of replacing are:

  • Often it's not enough to simply find a string which matches any upper- or lower case. E.g., for search results I need to replace it with the same case.
  • If I deal with innerHTML, I can easily damage HTML tags (e.g., an occurrence of hr in the href attribute).
  • The replaceAll() method is too fresh for many use cases, and it doesn't solve all the issues.

So, I was writing functions to highlight search results in a table, where table data cells may have links inside, as well as other HTML tags. And these links were intended to be kept, so innerText was not enough.

The solution I decided to provide for everyone with the same issues. Surely, you can use it not only for tables, but for any elements. Here is the code:

/* Iterate over table data cells to insert a highlight tag */
function highlightSearchResults(textFilter) {
  textFilter = textFilter.toLowerCase().replace('<', '&lt;').replace('>', '&gt;');
  let tds;
  tb = document.getElementById('sometable'); //root element where to search
  if (tb) {
    tds = tb.getElementsByTagName("td"); //sub-elements where to make replacements
  }
  if (textFilter && tds) {
    for (td of tds) {
      //specify your span class or whatever you need before and after
      td.innerHTML = insertCaseInsensitive(td.innerHTML, textFilter, '<span class="highlight">', '</span>');
    }
  }
}

/* Insert a highlight tag */
function insertCaseInsensitive(srcStr, lowerCaseFilter, before, after) {
  let lowStr = srcStr.toLowerCase();
  let flen = lowerCaseFilter.length;
  let i = -1;
  while ((i = lowStr.indexOf(lowerCaseFilter, i + 1)) != -1) {
    if (insideTag(i, srcStr)) continue;
    srcStr = srcStr.slice(0, i) + before + srcStr.slice(i, i+flen) + after + srcStr.slice(i+flen);
    lowStr = srcStr.toLowerCase();
    i += before.length + after.length;
  }
  return srcStr;
}

/* Check if an ocurrence is inside any tag by index */
function insideTag(si, s) {
  let ahead = false;
  let back = false;
  for (let i = si; i < s.length; i++) {
    if (s[i] == "<") {
      break;
    }
    if (s[i] == ">") {
      ahead = true;
      break;
    }
  }
  for (let i = si; i >= 0; i--) {
    if (s[i] == ">") {
      break;
    }
    if (s[i] == "<") {
      back = true;
      break;
    }
  }
  return (ahead && back);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alecx
  • 79
  • 1
  • 4
  • Related: [How can I dynamically highlight strings on a web page?](/a/32167527/4642212), [Find and replace specific text characters across a document with JS](/a/41886794/4642212). Both links are to my answers which go into quite a bit of depth as to how to replace text content in a document. – Sebastian Simon Dec 09 '21 at 11:52
  • Oh, those answers are more related to highlighting! However, I only found this replacing-related thread looking for some replacing solutions. Now I tried those functions: if I see correctly they do not highlight in a case-insensitive way, what i mean is: if phrases 'Text' or 'TEXT' (or even 'TexT', 'tExT', etc.) found, they should be highlighted as they are, without converting to lowercase/uppercase. The good thing about your code snippets that they work through the entire document and a ready-to-use solutions. These my functions should be adapted for one's needs and I think it's easy enough. – Alecx Dec 09 '21 at 19:58
-1

I would suggest adding a global method for the string class by appending it to the prototype chain.

String.prototype.replaceAll = function(fromReplace, toReplace, {ignoreCasing} = {}) { return this.replace(new RegExp(fromReplace, ignoreCasing ? 'ig': 'g'), toReplace);}

And it can be used like:

'stringwithpattern'.replaceAll('pattern', 'new-pattern')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohit Yadav
  • 463
  • 3
  • 7
  • Can you please elaborate what the above code is doing ? Try to give proper answers rather than one liners. – Khalid Khan Aug 25 '20 at 09:29
  • @KhalidKhan updated, anyways it was self explanatory but due to the delete vote, which was unnecessary, i updated the answer, whoever asked for delete might try to understand now. – Mohit Yadav Aug 25 '20 at 11:30
  • This doesn't work, `{ignoreCasing}` tries to destructure undefined in your example. And `this` doesn't refer to the string when using the arrow function – Jake Coxon Aug 25 '20 at 21:12
  • 1
    @JakeCoxon yeah my bad, updated the answer to fix the issues :D cheers! – Mohit Yadav Aug 26 '20 at 06:09
-2

Check this. I'm sure it will help you:

<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search and replace for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
  var str = 'Is this "3" dris "3"?';
  var allvar= '"3"';
  var patt1 = new RegExp( allvar, 'g' );
  document.getElementById("demo").innerHTML = str.replace(patt1,'"5"');
}
</script>
</body>
</html>

Here is the JSFiddle link.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ws Memon
  • 107
  • 7