JavaScript String replaceAll

[ad_1]

Changing a substring of textual content inside a bigger string has all the time been deceptive in JavaScript. I wrote Exchange 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 exchange solely replaces the primary incidence of a substring, not all occurrences. For instance:

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

To switch all situations of a substring, you have wanted to make use of a daily expression:

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

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

Fortunately, this 12 months the JavaScript language offered us with String.prototype.replaceAll, a way 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 state of affairs. I am glad they did so with replaceAll!

  • Chris Coyier’s Favorite CodePen Demos

    David requested me if I would be up for a visitor put up selecting out a few of my favourite Pens from CodePen. A frightening job! There are such a lot of! I managed to choose a number of although which have blown me away over the previous few months. For those who…

  • Vibration API

    Lots of the new APIs offered to us by browser distributors are extra focused towards the cellular consumer than the desktop consumer.  A type of easy APIs the Vibration API.  The Vibration API permits builders to direct the system, utilizing JavaScript, to vibrate in…

  • Send Email Notifications for Broken Images Using MooTools AJAX

    One of many little recognized JavaScript occasions is the picture onError occasion. This occasion is triggered when a picture 404’s out as a result of it does not exist. Damaged photographs could make your web site look unprofessional and it is necessary to repair damaged photographs as quickly as attainable.

  • Create a 3D Panorama Image with A-Frame

    Within the 5 years I have been at Mozilla I’ve seen some superior tasks.  A few of them very talked-about, a few of them very area of interest, however none of them has impressed me the way in which the MozVR staff’s work with WebVR and A-Body challenge have. A-Body is a group challenge…


[ad_2]

Leave a Reply