String.prototype.replaceAll | javascript string replace
Ifyou’veeverdealtwithstringsinJavaScript,chancesareyoucameacrosstheString#replacemethod.String.prototype.replace(searchValue,replacement)returnsastringwithsomematchesreplaced,basedontheparametersyouspecify:abc.replace(b,_);🍏🍋🍊🍓.replace(🍏,🥭);Acommonusecaseisreplacingallinstancesofagivensubstring.However,String#replacedoesn’tdirectlyaddressthisusecase.WhensearchValueisastring,onlythefirstoccurrenceofthesubstringgetsreplaced:aabbcc.replace(b,_);🍏🍏🍋🍋🍊🍊🍓🍓.replace(🍏,🥭);Toworkaroundthis,developerso...
If you’ve ever dealt with strings in JavaScript, chances are you came across the String#replace method. String.prototype.replace(searchValue, replacement) returns a string with some matches replaced, based on the parameters you specify:
abc.replace(b, _);🍏🍋🍊🍓.replace(🍏, 🥭);
A common use case is replacing all instances of a given substring. However, String#replace doesn’t directly address this use case. When searchValue is a string, only the first occurrence of the substring gets replaced:
aabbcc.replace(b, _);🍏🍏🍋🍋🍊🍊🍓🍓.replace(🍏, 🥭);
To work around this, developers often turn the search string into a regular expression with the global (g) flag. This way, String#replace does replace all matches:
aabbcc.replace(/b/g, _);🍏🍏🍋🍋🍊🍊🍓🍓.replace(/🍏/g, 🥭);
As a developer, it’s annoying to have to do this string-to-regexp conversion if all you really want is a global substring replacement. More importantly, this conversion is error-prone, and a common source of...