With the most recent version of v8, we now have several new JavaScript features available in all major browsers — one of which is String.prototype.replaceAll . It is used for replacing all occurrences of a given string or a regular expression with another string. It looks like this:

'lorem ipsum dolor sit amet'.replaceAll(' ', '-');
// -> 'lorem-ipsum-dolor-sit-amet'

It is a very simple addition to String.prototype.replace. Being the micro-optimization geek that I am, I decided to take a look at how this new feature performs compared to its alternatives. The purpose of this article, therefore, is to showcase this new feature and encourage the readers to approach new features from a different perspective.


What Were the Alternatives So Far?

Dating back to the early days of JavaScript, the prototype of String provided us with a function called replace that essentially does the same thing as replaceAll, but it replaces only the first occurrence of the searchValue. Example:

'lorem ipsum dolor sit amet'.replace(' ', '-');
// -> 'lorem-ipsum dolor sit amet'

This is useful but undesirable if you want to replace all occurrences of a text. One solution to that problem is to use a RegExp to define the searchValue . The same example as above can easily be rewritten with a RegExp to achieve the same behavior as replaceAll :

'lorem ipsum dolor sit amet'.replace(/ /g, '-');
// -> 'lorem-ipsum-dolor-sit-amet

#nodejs #programming #frontend #javascript #ecmascript

JavaScript: String.replaceAll has Landed in All Major Browsers
1.15 GEEK