Monday 24 October 2016

javascript - How to replace all occurrences of a string?



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?


Answer



Note: Don't use this 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://jsperf.com/replace-all-vs-split-join



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...