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?
Use a regular expression:
You could try combining this two powerful methods.
Hope it helps!
The following function works for me:
Now call the functions like this:
Simply copy and paste this code in your browser console to TEST.
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:Note: Don't use this in real code.
As an alternative to regular expressions for a simple literal string, you could use
The general pattern is
This used to be faster in some cases than using
replaceAll
and a regular expression, but that doesn't seem to be the case anymore in modern browsers. So, this should really only be used as a quick hack to avoid needing to escape the regular expression, not in real code.Replacing single quotes: