{{JSRef}}
The [@@search]()
method executes a search for a match between a this
regular expression and a string.
Syntax
regexp[Symbol.search](str)
Parameters
str
- A {{jsxref("String")}} that is a target of the search.
Return value
- integer
- If successful,
[@@search]()
returns the index of the first match of the regular expression inside the string. Otherwise, it returns -1.
Description
This method is called internally in {{jsxref("String.prototype.search()")}}. For example, following 2 code returns same result, and 1st case calls 2nd case internally.
'abc'.search(/a/); /a/[Symbol.search]('abc');
This method exists for customizing search behavior in RegExp subclass.
Examples
Call directly
This method can be used almost same way as {{jsxref("String.prototype.search()")}}, except different this
and arguments order.
var re = /-/g; var str = '2016-01-02'; var result = re[Symbol.search](str); console.log(result); // 4
Use in subclass
Subclass of {{jsxref("RegExp")}} can override [@@search]()
method to modify the behavior.
class MyRegExp extends RegExp { constructor(str) { super(str) this.pattern = str; } [Symbol.search](str) { return str.indexOf(this.pattern); } } var re = new MyRegExp('a+b'); var str = 'ab a+b'; var result = str.search(re); // String.prototype.search calls re[@@search]. console.log(result); // 3
Specifications
Specification | Status | Comment |
---|---|---|
{{SpecName('ES6', '#sec-regexp.prototype-@@search', 'RegExp.prototype[@@search]')}} | {{Spec2('ES6')}} | |
{{SpecName('ESDraft', '#sec-regexp.prototype-@@search', 'RegExp.prototype[@@search]')}} | {{Spec2('ESDraft')}} |
Browser compatibility
{{CompatibilityTable}}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{CompatUnknown}} | {{CompatGeckoDesktop(48)}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatUnknown}} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatGeckoMobile(48)}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatUnknown}} |
See also
- {{jsxref("String.prototype.search()")}}
- {{jsxref("RegExp.prototype.@@match()", "RegExp.prototype[@@match]()")}}
- {{jsxref("RegExp.prototype.@@replace()", "RegExp.prototype[@@replace]()")}}
- {{jsxref("RegExp.prototype.@@split()", "RegExp.prototype[@@split]()")}}
- {{jsxref("RegExp.prototype.exec()")}}
- {{jsxref("RegExp.prototype.test()")}}