Stop Using String Replace in JavaScript

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.

1_ZWd1kJQrO1dqCbNc1zKWYg.png


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.

1_imIdx1pCZbhzOSGs9nPfyQ.png

There are two workarounds to solve this problem.

Workaround one

Use regular expressions with a global flag.

1_IkzmRYAk8Zq-ct7_pQHKIA.png

Workaround two

Use String split with Array join.

1_UYfeCIAqX-CUUm38tBvdnQ.png

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.

1_hi6b83-XpD9M7WAMgoPjVw.png

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