JS: RegExp. prototype [Symbol.match]
What is RegExp.prototype symbol.match
RegExp.prototype[Symbol.match] do 2 things:
- It is called internally by
String.prototype.match. - It is used by many methods to determine if this-binding or argument is a regex object.
// these are equivalent console.log("abc".match(/a/)); // [ "a", index: 0, input: "abc", groups: undefined ] console.log(/a/[Symbol.match]("abc")); // [ "a", index: 0, input: "abc", groups: undefined ]
This means, you can customize String.prototype.match by adding a symbol property Symbol.match function to the regex object.
Check if a value is a regex object
RegExp.prototype[Symbol.match] is used by many methods to check if this-binding or argument is a regex object.
for an object to be considered as regex, it must have the property Symbol.match and also its value is true after force conversion by boolean constructor.
It is used by:
- String.prototype.startsWith → throws
TypeErrorif the argument is a regex. - String.prototype.endsWith → throws
TypeErrorif the argument is a regex. - String.prototype.includes → throws
TypeErrorif the argument is a regex. - String.prototype.matchAll → if the argument is a regex, requires the
gflag before proceeding. - String.prototype.replaceAll → if the argument is a regex, requires the
gflag before proceeding. - RegExp Constructor → uses the check to decide whether to return the same object, read
.source/.flags, or coerce to string.
Example. checking if it is regex
const xobj = new String("x"); xobj[Symbol.match] = true; console.log("abcd".startsWith(xobj)); // error: Uncaught TypeError: First argument to String.prototype.startsWith must not be a regular expression /* note, the errors says we are using regular expression. but we are not. we see that error because we added the property Symbol.match. */
Example. customized symbol.match
const xRegex = /a/; // customized match function. always return false xRegex[Symbol.match] = () => { console.log("am called."); return false; }; console.log("a".match(xRegex)); // am called. // false