snippetjavascriptCritical
How do I replace all occurrences of a string?
Viewed 0 times
replacehowoccurrencesstringall
Problem
Given a string:
This seems to only remove the first occurrence of
How do I replace all occurrences of it?
string = "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:string = string.replace('abc', '');How do I replace all occurrences of it?
Solution
In the latest versions of most popular browsers, you can use
as shown here:
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
The general pattern is
This used to be faster in some cases than using
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.
replaceAllas 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.
Context
Stack Overflow Q#1144783, score: 2410
Revisions (0)
No revisions yet.