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

瀏覽器相容性

另見