search() 方法执行正则表达式和 String对象之间的一个搜索匹配。
语法
str.search(regexp)
参数
regexp- 一个正则表达式(regular expression)对象。如果传入一个非正则表达式对象,则会使用 new RegExp(obj) 隐式地将其转换为正则表达式对象。
返回值
如果匹配成功,则 search() 返回正则表达式在字符串中首次匹配项的索引。否则,返回 -1。
描述
当你想要知道字符串中是否存在某个模式(pattern)时可使用 search,类似于正则表达式的 test 方法。当要了解更多匹配信息时,可使用 match(会更慢),该方法类似于正则表达式的 exec 方法。
示例
例子:使用 search
下例记录了一个消息字符串,该字符串的内容取决于匹配是否成功。
function testinput(re, str){
var midstring;
if (str.search(re) != -1){
midstring = " contains ";
} else {
midstring = " does not contain ";
}
console.log (str + midstring + re);
}
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 3rd Edition. | Standard | Initial definition. Implemented in JavaScript 1.2 |
| ECMAScript 5.1 (ECMA-262) String.prototype.search |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) String.prototype.search |
Standard |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Gecko特有事项
- 在Gecko 8.0及之前的版本,
search()实现有问题;当不传参数或者参数为undefined调用该方法时,该方法将不是匹配空字符串,而是对字符串"undefined"进行匹配。这个问题已被修复,现在"a".search()和"a".search(undefined)都能正确返回 0。