概要
search()
方法执行一个查找,看该字符串对象与一个正则表达式是否匹配。
语法
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-specific notes
- Prior to Gecko 8.0,
search()
was implemented incorrectly; when it was called with no parameters or withundefined
, it would match against the string "undefined", instead of matching against the empty string. This is fixed; now"a".search()
and"a".search(undefined)
correctly return 0.