試一試
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 |
瀏覽器相容性
載入中…