I have this string:
"Test abc test test abc test test test abc test test abc"
Doing
str = str.replace('abc', '');
seems to only remove the first occurrence of abc
in the string above. How can I replace all occurrences of it?
I have this string:
"Test abc test test abc test test test abc test test abc"
Doing
str = str.replace('abc', '');
seems to only remove the first occurrence of abc
in the string above. How can I replace all occurrences of it?
Just follow this oneliner regex adding the case-sensitivity, so if you do "ABC", it would act the same as that for "abc".
Here's a string prototype function based on the accepted answer:
EDIT
If your
find
will contain special characters then you need to escape them:Fiddle: http://jsfiddle.net/cdbzL/
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:
When complete, you will still have 'test abc'!
The simplest loop to solve this would be:
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:
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.]
In response to comment:
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:So in order to make the
replaceAll()
function above safer, it could be modified to the following if you also includeescapeRegExp
:I like this method (it looks a little cleaner):