此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
String.prototype.search()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
search() 方法用于在String 对象中执行正则表达式的搜索,寻找匹配项。
In this article
尝试一下
const paragraph = "I think Ruth's dog is cuter than your dog!";// Anything not a word character, whitespace or apostropheconst regex = /[^\w\s']/g;console.log(paragraph.search(regex));// Expected output: 41console.log(paragraph[paragraph.search(regex)]);// Expected output: "!"语法
js
search(regexp)参数
regexp一个正则表达式对象,或者具有
Symbol.search方法的任意对象。如果
regexp不是RegExp对象,并且不具有Symbol.search方法,则会使用new RegExp(regexp)将其隐式转换为RegExp。
返回值
如果匹配成功,则返回正则表达式在字符串中首次匹配的索引;否则,返回-1。
描述
String.prototype.search() 方法的实现非常简单——它只是将该字符串作为调用实参拥有的Symbol.search 方法的第一个参数。实际的实现来自于RegExp.prototype[Symbol.search]()。
regexp 的g 标志对search() 方法的结果没有影响,搜索总是以正则表达式的lastIndex 为 0 进行。有关search() 方法行为的更多信息,请参阅RegExp.prototype[Symbol.search]()。
当你想知道字符串中是否存在某个模式,并且还想知道它在字符串中的索引时,可以使用search() 方法。
- 如果你只想知道某个模式是否存在,请使用
RegExp.prototype.test()方法,它返回一个布尔值。 - 如果你需要获取匹配文本的内容,请使用
match()或RegExp.prototype.exec()。
示例
>使用 search()
下面的示例中用两个不同的正则表达式对同一个字符串执行搜索匹配,得到一个成功匹配(正数返回值)和一个失败匹配(-1)。
js
const str = "hey JudE";const re = /[A-Z]/;const reDot = /[.]/;console.log(str.search(re)); // 返回 4,这是第一个大写字母“J”的索引console.log(str.search(reDot)); // 返回 -1,找不到点符号“.”规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-string.prototype.search> |