JavaScript String replace vs replaceAll

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)