String operations and RegExp symbol hooks
Quick answer
String matching methods delegate to symbol-keyed hooks when provided. RegExp implements these hooks, but custom objects can implement them too.
How it works
match, matchAll, replace, search and split consult Symbol.match, Symbol.matchAll, Symbol.replace, Symbol.search and Symbol.split respectively. The hook receives the string and, where applicable, a replacement or limit. Some string methods perform extra checks (for example matchAll requires a global RegExp). IsRegExp may consult Symbol.match; a custom hook need not follow ordinary regex output conventions, so callers must document the contract.
const marker={ [Symbol.search](s){return s.indexOf("!");} }; console.log("ab!c".search(marker));Expected output in Node.js:
2The custom search hook returns the index.
const custom={ [Symbol.replace](s,repl){return repl+":"+s;} }; console.log("abc".replace(custom,"X"));Expected output in Node.js:
X:abcThe replacement hook controls the returned value.
Common mistakes
Do not assume a custom match result is always a RegExp match array. Avoid overriding standard hooks just to rename simple functions.
Practice
Implement a search hook for a fixed prefix and compare its return value with ordinary search.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
String operations and RegExp symbol hooks — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which hook does String.prototype.split consult?
Which flag is required for a RegExp passed to matchAll?
Can a custom search hook return its own number?
What is the exact console output in String operations and RegExp symbol hooks example 1?
const marker={ [Symbol.search](s){return s.indexOf("!");} }; console.log("ab!c".search(marker));What is the exact console output in String operations and RegExp symbol hooks example 2?
const custom={ [Symbol.replace](s,repl){return repl+":"+s;} }; console.log("abc".replace(custom,"X"));