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?
http://jsfiddle.net/ANHR9/
Using a regular expression with the
g
flag set will replace all:See here also
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, asreplace(...)
just returns result, but not overrides. In some cases you might want to use that.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
You can refer the detailed example here.
Or try the replaceAll function from here:
What are useful JavaScript methods that extends built-in objects?
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.
E.g.