JS: RegExp. prototype [Symbol.search]

By Xah Lee. Date: .

What is RegExp.prototype symbol.search

RegExp.prototype[Symbol.search] is the method that defines how String.prototype.search() behaves with a regular expression.

// these are equivalent

console.log(/a/[Symbol.search]("cat"));
// 1

console.log("cat".search(/a/));
// 1

Example. customized symbol.search

const xRegex = /a/;

// customized search function. always return false
xRegex[Symbol.search] = () => {
 console.log("am called");
 return false;
};

// call String.prototype.search
console.log("a".search(xRegex));
// am called
// false