JavaScript String replaceAll

By  on  

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!

Recent Features

Incredible Demos

  • By
    Element Position Swapping Using MooTools 1.2

    We all know that MooTools 1.2 can do some pretty awesome animations. What if we want to quickly make two element swap positions without a lot of fuss? Now you can by implementing a MooTools swap() method. MooTools 1.2 Implementation MooTools 1.2 Usage To call the swap...

  • By
    Fancy FAQs with jQuery Sliders

    Frequently asked questions can be super boring, right? They don't have to be! I've already shown you how to create fancy FAQs with MooTools -- here's how to create the same effect using jQuery. The HTML Simply a series of H3s and DIVs wrapper...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!