Question
Given a string:
s = "Test abc test test abc test test test abc test test abc";
This seems to only remove the first occurrence of abc
in the string above:
s = s.replace('abc', '');
How do I replace all occurrences of it?
Answer
In the latest versions of most popular browsers, you can use
[replaceAll
](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) 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.js 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
str.split(search).join(replacement)
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.
Benchmark: https://jsben.ch/TZYzj
Conclusion:
If you have a performance-critical use case (e.g., processing hundreds of strings), use the regular expression method. But for most typical use cases, this is well worth not having to worry about special characters.