JS: String.prototype.search

By Xah Lee. Date: . Last updated: .
str.search(regex_or_str)
  • Return the index of first char of matched string.
  • If no match, returns -1.

If argument is a string, it is converted to regex object by the regex constructor RegExp.

// find digit
console.log(
 "a 34 b".search(/\d/),
);
// 2

// not found
console.log(
 "a 34 b".search(/xx/),
);
// -1
// using string as arg
console.log(
 "a 34 b".search("\\d"),
);
// 2

Symbol.search property

🛑 warning: String.prototype.search internally calls RegExp.prototype[Symbol.search].

It means, you can customize String.prototype.search by adding a symbol property Symbol.search function to the regex object.