Home Software Development JavaScript String replaceAll

JavaScript String replaceAll

0
JavaScript String replaceAll

Changing a substring of textual content inside a bigger string has at all times been deceptive in JavaScript. I wrote Exchange All Occurrences of a String in JavaScript years in the past and it is nonetheless one in all my most learn articles.

The confusion lies in that exchange solely replaces the primary prevalence of a substring, not all occurrences. For instance:

'yayayayayaya'.exchange('ya', 'na');
// nayayayayaya

To switch all situations of a substring, you’ve got wanted to make use of an everyday expression:

'yayayayayaya'.exchange(/ya/g, 'na');
// nananananana

Utilizing common expressions is actually highly effective however let’s be trustworthy — oftentimes we merely need to exchange all situations of a easy substring that should not require an everyday expression.

Fortunately, this yr the JavaScript language supplied us with String.prototype.replaceAll, a technique for changing with out utilizing common expressions:

'yayayayayaya'.replaceAll('ya', 'na');
// nananananana

Generally an API exists in a complicated format and requirements our bodies merely want to enhance the scenario. I am glad they did so with replaceAll!

  • CSS @supports

    Function detection by way of JavaScript is a consumer aspect finest observe and for all the precise causes, however sadly that very same performance hasn’t been accessible inside CSS.  What we find yourself doing is repeating the identical properties a number of occasions with every browser prefix.  Yuck.  One other factor we…

  • 9 More Mind-Blowing WebGL Demos