Date:

Share:

JavaScript String replaceAll

Related Articles

Replacing a text sub-string within a larger string has always been misleading in JavaScript. I wrote replace all the occurrences of a string in JavaScript years ago and it’s still one of my most read articles.

The confusion lies in that replace Replaces only the first instance of a sub-string, no all Occurrences. for example:

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

To replace all instances of a sub-string, you had to use a regular expression:

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

The use of regular expressions is certainly powerful, but let’s be honest – we often just want to replace all instances of a simple sub-string that should not require regular expression.

Luckily, this year the JavaScript language provided us String.prototype.replaceAll, A method of replacement without the use of regular expressions:

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

Sometimes an API exists in a confusing format and device entities just need to improve the situation. I’m glad they did it with replaceAll!

  • 9 more exciting WebGL demos
  • Facebook Open Graph META Tags

    Facebook Open Graph META Tags

    It’s no secret that Facebook has become a major driving force for all types of sites. Today even large corporations direct consumers towards their Facebook pages instead of to the corporate websites directly. And of course there are “liked” and “recommended” widgets on every Facebook site. one…


Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles