String.prototype.replaceAll() – JavaScript | MDN

This method does not mutate the string value it’s called on. It returns a new string.

Unlike replace(), this method would replace all occurrences of a string, not just the first one. This is especially useful if the string is not statically known, as calling the RegExp() constructor without escaping special characters may unintentionally change its semantics.

function

unsafeRedactName

(

text

,

name

)

{

return

text

.

replace

(

new

RegExp

(

name

,

"g"

)

,

"[REDACTED]"

)

;

}

function

safeRedactName

(

text

,

name

)

{

return

text

.

replaceAll

(

name

,

"[REDACTED]"

)

;

}

const

report

=

"A hacker called ha.*er used special characters in their name to breach the system."

;

console

.

log

(

unsafeRedactName

(

report

,

"ha.*er"

)

)

;

console

.

log

(

safeRedactName

(

report

,

"ha.*er"

)

)

;

If pattern is an object with a Symbol.replace method (including RegExp objects), that method is called with the target string and replacement as arguments. Its return value becomes the return value of replaceAll(). In this case the behavior of replaceAll() is entirely encoded by the @@replace method, and therefore will have the same result as replace() (apart from the extra input validation that the regex is global).

If the pattern is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to split() behavior.

"xxx"

.

replaceAll

(

""

,

"_"

)

;

For more information about how regex properties (especially the sticky flag) interact with replaceAll(), see RegExp.prototype[@@replace]().