JavaScript String replaceAll

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: […]

The post JavaScript String replaceAll appeared first on David Walsh Blog.

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.replaceAll, a 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!

The post JavaScript String replaceAll appeared first on David Walsh Blog.


Print Share Comment Cite Upload Translate
APA
David Walsh | Sciencx (2024-03-29T11:50:27+00:00) » JavaScript String replaceAll. Retrieved from https://www.scien.cx/2021/12/27/javascript-string-replaceall/.
MLA
" » JavaScript String replaceAll." David Walsh | Sciencx - Monday December 27, 2021, https://www.scien.cx/2021/12/27/javascript-string-replaceall/
HARVARD
David Walsh | Sciencx Monday December 27, 2021 » JavaScript String replaceAll., viewed 2024-03-29T11:50:27+00:00,<https://www.scien.cx/2021/12/27/javascript-string-replaceall/>
VANCOUVER
David Walsh | Sciencx - » JavaScript String replaceAll. [Internet]. [Accessed 2024-03-29T11:50:27+00:00]. Available from: https://www.scien.cx/2021/12/27/javascript-string-replaceall/
CHICAGO
" » JavaScript String replaceAll." David Walsh | Sciencx - Accessed 2024-03-29T11:50:27+00:00. https://www.scien.cx/2021/12/27/javascript-string-replaceall/
IEEE
" » JavaScript String replaceAll." David Walsh | Sciencx [Online]. Available: https://www.scien.cx/2021/12/27/javascript-string-replaceall/. [Accessed: 2024-03-29T11:50:27+00:00]
rf:citation
» JavaScript String replaceAll | David Walsh | Sciencx | https://www.scien.cx/2021/12/27/javascript-string-replaceall/ | 2024-03-29T11:50:27+00:00
https://github.com/addpipe/simple-recorderjs-demo