September 26, 2022

Robotic Notes

All technology News

JavaScript String replaceAll

2 min read

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.replaceAlla 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!!

Website performance monitoring
Website performance monitoring
Website performance monitoring
Website performance monitoring
  • I & # 8217; m an Impostor

    I’m an Impostor

    This is the hardest thing I’ve ever had to write, much less admit to myself. I’ve written resignation letters from jobs I’ve loved, I’ve ended relationships, I’ve failed at a host of tasks, and let myself down in my life. All of those feelings were very …

  • fetch API

    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn’t really made for what we’ve been using it for. We’ve done well to create elegant APIs around XHR but we know we can do better. Our effort to …

  • : valid,: invalid, and: required CSS Pseudo Classes

    : valid,: invalid, and: required CSS Pseudo Classes

    Let’s be honest, form validation with JavaScript can be a real bitch. On a real basic level, however, it’s not that bad. HTML5 has jumped to some extent, providing a few attributes to allow us to mark fields as required or only valid if matching …

  • Fade Images with MooTools LazyLoad

    Fade Images with MooTools LazyLoad

    I recently received an email from a MooTools developer asking a great question about my LazyLoad class: “I’m using your LazyLoad MooTools plugin (which is great, by the way). I have been trying to figure out how to modify it so that once an image scrolls into …



Source link