Posted By: Anonymous
"Test abc test test abc test test test abc test test abc"
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?
Update: In the latest versions of most popular browsers, you can use
as shown here:
let result = "1 abc 2 abc 3".replaceAll("abc", "xyz"); // `result` is "1 xyz 2 xyz 3"
But check Can I use or another compatibility table first to make sure the browsers you’re targeting have added support for it first.
For Node and compatibility with older/non-current browsers:
Note: Don’t use the following solution in performance critical code.
As an alternative to regular expressions for a simple literal string, you could use
str = "Test abc test test abc test...".split("abc").join("");
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.
Conclusion: If you have a performance critical use case (e.g processing hundreds of strings), use the Regexp method. But for most typical use cases, this is well worth not having to worry about special characters.