JS: RegExp. prototype [Symbol.match]

By Xah Lee. Date: .

What is RegExp.prototype symbol.match

RegExp.prototype[Symbol.match] do 2 things:

// 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:

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