Given a string:
string = "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:
string = string.replace('abc', '');
How do I replace all occurrences of it?
javascriptreplacestring
Given a string:
string = "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:
string = string.replace('abc', '');
How do I replace all occurrences of it?
Best Answer
As of August 2020: Modern browsers have support for the
String.replaceAll()
method defined by the ECMAScript 2021 language specification.For older/legacy browsers:
Here is how this answer evolved:
In response to comment "what's if 'abc' is passed as a variable?":
In response to Click Upvote's comment, you could simplify it even more:
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):So in order to make the
replaceAll()
function above safer, it could be modified to the following if you also includeescapeRegExp
: