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?
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.
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/
Use a regular expression:
The simplest way to this without using any regex is split and join like code here :
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.