Stop Using String Replace in JavaScript
Why you should use replaceAll when replacing multiple instances of a substring
Cover Photo by David Ragusa on Unsplash
Introduction
If you are a JavaScript developer, you would have definitely dealt with strings. If you have dealt with strings, you would have come across the string replace
method.
This method returns a string with some matches replaced based on the parameters you specified. This is the syntax: replace(searchValue,newValue)
.
In this article, I will explain why the String.prototype.replaceAll
method is necessary and why you should start using it.
Start
Look at the below code. This is the implementation of the simple String replace
method.
Where Does replaceAll Come Into Play?
When you work with strings, a common use case is replacing all instances of a given substring.
However, String replace
does not directly address this use case. When the first input parameter is a string, only the first match of the substring gets replaced.
There are two workarounds to solve this problem.
Workaround one
Use regular expressions with a global flag.
Workaround two
Use String split with Array join.
Both these workarounds have their drawbacks. Strings with special regex characters such as +
are not as simple as removing the quotes and wrapping them with /
.
They can get complicated with more special characters. The split join method has unnecessary overheads associated with splitting the string and attaching them back together. Clearly, none of these workarounds is ideal.
Introducing replaceAll
The newly introduced replaceAll
method solves all these problems with a simple and straightforward solution.
Conclusion
String.prototype.replaceAll
enriches JavaScript with first-class support for global substring replacement, without the need for regular expressions or other workarounds.
This feature was added in November 2019 and is currently supported only with Babel.js.
References