Skip to content Skip to sidebar Skip to footer

JavaScript String Replace Vs ReplaceAll

ECMAScript 2021 has added a new String function replaceAll. A long time ago in a galaxy not so far away, people used split + join or regular expressions to replace all occurences o

Solution 1:

From gleaning the documentation for replaceAll, we find the following tidbits:

const newStr = str.replaceAll(regexp|substr, newSubstr|function)

Note: When using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

In other words, when calling replaceAll with a regex literal or RegExp, it must use the global flag. So, there doesn't seem to be much gained by calling replaceAll versus just using the current replace. However, one difference with replaceAll is that when passing it a string, it will automatically do a global replacement. This is where you might save yourself a bit of typing, by not having to enter a global flag.


Post a Comment for "JavaScript String Replace Vs ReplaceAll"