Replacing a substring of text within a larger string has always been misleading in JavaScript. I wrote Replace All Occurrences of a String in JavaScript years ago and it’s still one of my most read articles.
The confusion lies in that replace
only replaces the first occurrence of a substring, not all occurrences. For example:
'yayayayayaya'.replace('ya', 'na'); // nayayayayaya
To replace all instances of a substring, you’ve needed to use a regular expression:
'yayayayayaya'.replace(/ya/g, 'na'); // nananananana
Using regular expressions is certainly powerful but let’s be honest — oftentimes we simply want to replace all instances of a simple substring that shouldn’t require a regular expression.
Luckily, this year the JavaScript language provided us with String.prototype.replaceAll
, a method for replacing without using regular expressions:
'yayayayayaya'.replaceAll('ya', 'na'); // nananananana
Sometimes an API exists in a confusing format and standards bodies simply need to improve the situation. I’m glad they did so with replaceAll
!
Conquering Impostor Syndrome
Two years ago I documented my struggles with Imposter Syndrome and the response was immense. I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions. I’ve even caught myself reading the post…
Geolocation API
One interesting aspect of web development is geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user’s location. Let’s examine how you can…
Source link