pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/search

dule">

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

String.prototype.search()

基线 广泛可用

自 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 方法,则会使用 new RegExp(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)); // 返回 4,这是第一个大写字母“J”的索引
console.log(str.search(reDot)); // 返回 -1,找不到点符号“.”

规范

规范
ECMAScript® 2027 Language Specification
# sec-string.prototype.search

浏览器兼容性

参见

pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy