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
!
Responsive and Infinitely Scalable JS Animations
Back in late 2012 it was not easy to find open source projects using
requestAnimationFrame()
– this is the hook that allows Javascript code to synchronize with a web browser’s native paint loop. Animations using this method can run at 60 fps and deliver fantastic…How I Stopped WordPress Comment Spam
I love almost every part of being a tech blogger: learning, preaching, bantering, researching. The one part about blogging that I absolutely loathe: dealing with SPAM comments. For the past two years, my blog has registered 8,000+ SPAM comments per day. PER DAY. Bloating my database…
CSS pointer-events
The responsibilities taken on by CSS seems to be increasingly blurring with JavaScript. Consider the
-webkit-touch-callout
CSS property, which prevents iOS’s link dialog menu when you tap and hold a clickable element. Thepointer-events
property is even more JavaScript-like, preventing: click actions from doing…Spoiler Prevention with CSS Filters
No one likes a spoiler. Whether it be an image from an upcoming film or the result of a football match you DVR’d, sometimes you just don’t want to know. As a possible provider of spoiler content, some sites may choose to warn users ahead…