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?
If what you want to find is already in a string, and you don't have a regex escaper handy, you can use join/split:
These are the most common and readable methods.
Method-01:
Method-02:
Method-03:
Method-04:
Output:
Replacing single quotes:
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.
If the string contain similar pattern like
abccc
, you can use this:Update:
It's somewhat late for an update, but since I just stumbled on this question, and noticed that my previous answer is not one I'm happy with. Since the question involved replaceing a single word, it's incredible nobody thought of using word boundaries (
\b
)This is a simple regex that avoids replacing parts of words in most cases. However, a dash
-
is still considered a word boundary. So conditionals can be used in this case to avoid replacing strings likecool-cat
:basically, this question is the same as the question here: Javascript replace " ' " with " '' "
@Mike, check the answer I gave there... regexp isn't the only way to replace multiple occurrences of a subsrting, far from it. Think flexible, think split!
Alternatively, to prevent replacing word parts -which the approved answer will do, too! You can get around this issue using regular expressions that are, I admit, somewhat more complex and as an upshot of that, a tad slower, too:
The output is the same as the accepted answer, however, using the /cat/g expression on this string:
Oops indeed, this probably isn't what you want. What is, then? IMHO, a regex that only replaces 'cat' conditionally. (ie not part of a word), like so:
My guess is, this meets your needs. It's not fullproof, of course, but it should be enough to get you started. I'd recommend reading some more on these pages. This'll prove useful in perfecting this expression to meet your specific needs.
http://www.javascriptkit.com/jsref/regexp.shtml
http://www.regular-expressions.info
Final addition:
Given that this question still gets a lot of views, I thought I might add an example of
.replace
used with a callback function. In this case, it dramatically simplifies the expression and provides even more flexibility, like replacing with correct capitalisation or replacing bothcat
andcats
in one go: