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
!
An Interview with Eric Meyer
Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer…
Create Namespaced Classes with MooTools
MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does. Many developers create their classes as globals which is generally frowned up. I mostly disagree with that stance, but each to their own. In any event…
Add Styles to Console Statements
I was recently checking out Google Plus because they implement some awesome effects. I opened the console and same the following message: WARNING! Using this console may allow attackers to impersonate you and steal your information using an attack called Self-XSS. Do not enter or paste code that you…
Making the Firefox Logo from HTML
When each new t-shirt means staving off laundry for yet another day, swag quickly becomes the most coveted perk at any tech company. Mozilla WebDev had pretty much everything going for it: brilliant people, interesting problems, awesome office. Everything except a t-shirt. That had to change. The basic…
Source link