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
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Incredible Demos

  • By
    RealTime Stock Quotes with MooTools Request.Stocks and YQL

    It goes without saying but MooTools' inheritance pattern allows for creation of small, simple classes that possess immense power.  One example of that power is a class that inherits from Request, Request.JSON, and Request.JSONP:  Request.Stocks.  Created by Enrique Erne, this great MooTools class acts as...

  • By
    MooTools dwCheckboxes Plugin

    Update / Fix: The checkboxes will no longer toggle when the "mouseup" event doesn't occur on a checkbox. Every morning I wake up to a bunch of emails in my Gmail inbox that I delete without reading. I end up clicking so many damn checkboxes...

Discussion

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