String.prototype.search()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

search() 方法用于在 String 值中搜索与正则表达式匹配的内容,并返回第一个匹配项在字符串中的索引。

试一试

const paragraph = "I think Ruth's dog is cuter than your dog!";

// Anything not a word character, whitespace or apostrophe
const regex = /[^\w\s']/g;

console.log(paragraph.search(regex));
// Expected output: 41

console.log(paragraph[paragraph.search(regex)]);
// Expected output: "!"

语法

js
search(regexp)

参数

regexp

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

如果 regexp 不是 RegExp 对象,也没有 Symbol.search 方法,它会被隐式地转换为一个 RegExp 对象,通过使用 new RegExp(regexp)

返回值

正则表达式与给定字符串的第一个匹配项的索引,如果没有找到匹配项,则返回 -1

描述

String.prototype.search() 的实现除了调用参数的 Symbol.search 方法并将字符串作为第一个参数之外,并没有做太多其他事情。实际的实现来自 RegExp.prototype[Symbol.search]()

regexpg 标志对 search() 的结果没有影响,搜索始终像正则表达式的 lastIndex 为 0 一样进行。有关 search() 行为的更多信息,请参阅 RegExp.prototype[Symbol.search]()

当您想知道一个模式是否被找到,并且想知道它在字符串中的索引时,请使用 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

规范

规范
ECMAScript® 2026 语言规范
# sec-string.prototype.search

浏览器兼容性

另见