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?
Using a regular expression with the
g
flag set will replace all:See here also
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.]
I like this method (it looks a little cleaner):
Just add
/g
to
/g
means globalFor replacing a single time use:
For replacing multiple times use:
Say you want to replace all the 'abc' with 'x':
I was trying to think about something more simple than modifying the string prototype.