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

语法

¥Syntax

js
search(regexp)

参数

¥Parameters

regexp

正则表达式对象,或任何具有 Symbol.search 方法的对象。

如果 regexp 不是 RegExp 对象并且没有 Symbol.search 方法,则使用 new RegExp(regexp) 将其隐式转换为 RegExp

返回值

¥Return value

正则表达式和给定字符串之间的第一个匹配项的索引,如果未找到匹配项,则为 -1

¥The index of the first match between the regular expression and the given string, or -1 if no match was found.

描述

¥Description

String.prototype.search() 本身的实现非常简单 - 它只是调用参数的 Symbol.search 方法,并将字符串作为第一个参数。实际实现来自 RegExp.prototype[@@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[@@search]().

regexpg 标志对 search() 结果没有影响,并且搜索总是像正则表达式的 lastIndex 为 0 一样进行。有关 search() 行为的更多信息,请参阅 RegExp.prototype[@@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[@@search]().

当你想知道是否找到某个模式,并且还想知道它在字符串中的索引时,请使用 search()

¥When you want to know whether a pattern is found, and also know its index within a string, use search().

示例

¥Examples

使用搜索()

¥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).

js
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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看