search() 方法执行正则表达式和 String 对象之间的一个搜索匹配。

语法

str.search(regexp)

参数

regexp
一个正则表达式(regular expression)对象。如果传入一个非正则表达式对象 obj,则会使用 new RegExp(obj) 隐式地将其转换为正则表达式对象。

返回值

如果匹配成功,则 search() 返回正则表达式在字符串中首次匹配项的索引;否则,返回 -1

描述

当你想要知道字符串中是否存在某个模式(pattern)时可使用 search(),类似于正则表达式的 test() 方法。当要了解更多匹配信息时,可使用 match()(但会更慢一些),该方法类似于正则表达式的 exec() 方法。

示例

例子:使用 search()

The following example searches a string with 2 different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1)

var str = "hey JudE";
var re = /[A-Z]/g;
var re2 = /[.]/g;
console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
console.log(str.search(re2)); // returns -1 cannot find '.' dot punctuation

规范

规范 状态 备注
ECMAScript 3rd Edition (ECMA-262) 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  
ECMAScript Latest Draft (ECMA-262)
String.prototype.search
Draft  

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
searchChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes
flags
DeprecatedNon-standard
Chrome No support NoEdge No support NoFirefox No support 1 — 49IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoEdge Mobile No support NoFirefox Android No support 4 — 49Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support Nonodejs No support No

Legend

Full support  
Full support
No support  
No support
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.

Gecko 注意事项

参见