String.prototype.search()
search()
方法执行正则表达式和 String
对象之间的一个搜索匹配。
尝试一下
语法
str.search(regexp)
参数
regexp
-
一个
正则表达式(regular expression)
对象。如果传入一个非正则表达式对象regexp
,则会使用new RegExp(regexp)
隐式地将其转换为正则表达式对象。
返回值
如果匹配成功,则 search()
返回正则表达式在字符串中首次匹配项的索引;否则,返回 -1
。
描述
示例
例子:使用 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
规范
Specification |
---|
ECMAScript Language Specification # sec-string.prototype.search |
浏览器兼容性
BCD tables only load in the browser