JS: RegExp. prototype [Symbol.replace]

By Xah Lee. Date: .

What is RegExp.prototype symbol.replace

RegExp.prototype[Symbol.replace] is the method that defines how String.prototype.replace() and String.prototype.replaceAll() work when the pattern is a regular expression.

// these are equivalent

console.log(
 /\d/g[Symbol.replace]("3 cats", "x"),
);
// x cats

console.log(
 "3 cats".replace(/\d/g, "x"),
);
// x cats

This means, you can customize them by adding a symbol property Symbol.replace function to the regex object.

Behavior

Example. customized symbol.replace

const xRegex = /a/;

// customized replace function. always return false
xRegex[Symbol.replace] = () => false;

console.log("a".replace(xRegex));
// false