RegExp.prototype[@@search]() - JavaScript 编辑
[@@search]()
方法执行了一个在给定字符串中的一个搜索以取得匹配正则模式的项。
语法
regexp[Symbol.search](str)
参数
str
- 搜索的目标
String
。
返回值
- 整数
- 如果成功的话,
[@@search]()
返回该正则模式的第一个匹配项的在字符串中的位置索引。否则将返回-1。
描述
这个方法在 String.prototype.search()
的内部调用。例如,下面的两个方法返回相同结果。
'abc'.search(/a/);
/a/[Symbol.search]('abc');
这个方法为自定义 RegExp
子类中的匹配行为而存在。
示例
直接调用
这个方法的使用方式和 String.prototype.search()
相同,不同之处是 this
和参数顺序。
var re = /-/g;
var str = '2016-01-02';
var result = re[Symbol.search](str);
console.log(result); // 4
在子类中使用@@search
{jsxref("RegExp")}} 的子类可以覆写 [@@search]()
方法来修改默认行为。
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
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) RegExp.prototype[@@search] | Standard | 初始定义 |
ECMAScript Latest Draft (ECMA-262) RegExp.prototype[@@search] | Draft |
浏览器兼容性
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | ? | 49 (49) | ? | ? | ? |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | ? | ? | 49.0 (49) | ? | ? | ? |
另见
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论