JS: RegExp. prototype [Symbol.replace]
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
- If the regex has Regex Flag
g(global),lastIndexis reset to 0 andexec()is called repeatedly until it returnsnull. - Empty matches advance
lastIndex(by one Unicode code point if unicode flag u or v is on, otherwise one UTF-16 code unit). - If not global,
exec()runs only once. - Special replacement patterns (
$&,$1, etc.) and function replacements work the same way as withString.prototype.replace. - Sticky (
y) regexes interact withlastIndexand can produce different results across calls if not global.
Example. customized symbol.replace
const xRegex = /a/; // customized replace function. always return false xRegex[Symbol.replace] = () => false; console.log("a".replace(xRegex)); // false