String.prototype.search()
String 值的 search() 方法执行正则表达式与此字符串之间的匹配搜索,返回字符串中第一个匹配的索引。
¥The search() method of String values executes a search for a match between a regular expression and this string, returning the index of the first match in the string.
Try it
语法
参数
¥Parameters
regexp-
正则表达式对象,或任何具有
Symbol.search方法的对象。如果
regexp不是RegExp对象并且没有Symbol.search方法,则使用new RegExp(regexp)将其隐式转换为RegExp。
返回值
描述
¥Description
String.prototype.search() 本身的实现非常简单 - 它只是调用参数的 Symbol.search 方法,并将字符串作为第一个参数。实际实现来自 RegExp.prototype[Symbol.search]()。
¥The implementation of String.prototype.search() itself is very simple — it simply calls the Symbol.search method of the argument with the string as the first parameter. The actual implementation comes from RegExp.prototype[Symbol.search]().
regexp 的 g 标志对 search() 结果没有影响,并且搜索总是像正则表达式的 lastIndex 为 0 一样进行。有关 search() 行为的更多信息,请参阅 RegExp.prototype[Symbol.search]()。
¥The g flag of regexp has no effect on the search() result, and the search always happens as if the regex's lastIndex is 0. For more information on the behavior of search(), see RegExp.prototype[Symbol.search]().
当你想知道是否找到某个模式,并且还想知道它在字符串中的索引时,请使用 search()。
¥When you want to know whether a pattern is found, and also know its index within a string, use search().
- 如果你只想知道它是否存在,请使用
RegExp.prototype.test()方法,该方法返回一个布尔值。 - 如果需要匹配文本的内容,请使用
String.prototype.match()或RegExp.prototype.exec()。
示例
使用搜索()
¥Using search()
以下示例使用两个不同的正则表达式对象搜索字符串,以显示成功的搜索(正值)与不成功的搜索(-1)。
¥The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1).
const str = "hey JudE";
const re = /[A-Z]/;
const reDot = /[.]/;
console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
console.log(str.search(reDot)); // returns -1 cannot find '.' dot punctuation
规范
| Specification |
|---|
| ECMAScript Language Specification # sec-string.prototype.search |
浏览器兼容性
BCD tables only load in the browser