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
RegExp
in JavaScript could do the job for you, just simply do something like below: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 get use of 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.
//loop it until number occurrences comes to 0. OR simply copy/paste
Just add
/g
to
/g
means globalYou can simply use below method
Match against a global regular expression:
Say you want to replace all the 'abc' with 'x':
I was trying to think about something more simple than modifying the string prototype.