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?
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
:Match against a global regular expression:
Using
RegExp
in JavaScript could do the job for you, just simply do something like below code, don't forget the/g
after which standout for global:If you think of reuse, create a function to do that for you, but it's not recommended as it's only one line function, but again if you heavily use this, you can write something like this:
and simply use it in your code over and over like below:
But as I mention earlier, it won't make a huge difference in terms of lines to be written or performance, only caching the function may effect some faster performance on long strings and also a good practice of DRY code if you want to reuse.
You can simply use below method
//loop it until number occurrences comes to 0. OR simply copy/paste
http://jsfiddle.net/ANHR9/