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

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

  • By
    Ana Tudor’s Favorite CodePen Demos

    Cocoon I love canvas, I love interactive demos and I don't think I have ever been more impressed by somebody's work than when I discovered what Tiffany Rayside has created on CodePen. So I had to start off with one of her interactive canvas pens, even though...

  • By
    MooTools Typewriter Effect Plugin

    Last week, I read an article in which the author created a typewriter effect using the jQuery JavaScript framework. I was impressed with the idea and execution of the code so I decided to port the effect to MooTools. After about an hour of coding...

Discussion

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