试一试
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]()。
regexp 的 g 标志对 search() 的结果没有影响,搜索始终像正则表达式的 lastIndex 为 0 一样进行。有关 search() 行为的更多信息,请参阅 RegExp.prototype[Symbol.search]()。
当您想知道一个模式是否被找到,并且还想知道它在字符串中的索引时,请使用 search()。
- 如果您只想知道它是否存在,请使用
RegExp.prototype.test()方法,该方法返回一个布尔值。 - 如果您需要匹配文本的内容,请使用
String.prototype.match()或RegExp.prototype.exec()。
示例
使用 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 |
浏览器兼容性
加载中…