HomeSoftware DevelopmentJavaScript String replaceAll

JavaScript String replaceAll

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

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

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

To switch all cases of a substring, you’ve got wanted to make use of a daily expression:

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

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

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

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

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

  • MooTools Clipboard Plugin

    The flexibility to position content material right into a person’s clipboard might be extraordinarily handy for the person. As a substitute of clicking and dragging down what may very well be a prolonged doc, the person can copy the contents of a selected space by a single click on of a mouse.

  • Jack Rugile’s Favorite CodePen Demos

    CodePen is an incredible supply of inspiration for code and design. I’m blown away daily by the demos customers create. As you will see beneath, I’ve an affinity towards issues that transfer. It was tough to slender down my favorites, however right here they’re!



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments