萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript String.prototype.search() 完整指南:正則搜尋首次匹配位置

前言

search() 執行正則搜尋,回傳第一個匹配的索引。找不到回傳 -1。類似 indexOf() 但支援正則,不支援全域搜尋(忽略 g 旗標)。

語法

str.search(regexp)

參數與回傳

  • regexp:RegExp 物件或字串(隱式轉 RegExp)。
  • 回傳:首次匹配索引 (0-based),找不到為 -1。

程式碼範例

<script>
const str = 'Apples are round, and apples are juicy.';
const re = /apples/gi;

const idx = str.search(re);
if (idx !== -1) {
  console.log(`Found at index ${idx}`); // Found at index 0
} else {
  console.log('Not found');
}

// 僅檢查是否包含
const hasApples = str.search(/apples/i) !== -1;
console.log(hasApples); // true
</script>

與 indexOf()、test() 比較

方法支援正則回傳值用途
search()是索引 / -1找位置、需正則模式
indexOf()否索引 / -1簡單子字串找位置、效能最好
test()是true/false僅檢查是否匹配、效能最好
match()是陣列/null擷取匹配內容/群組

注意事項

  • search() 忽略 g 旗標,永遠從索引 0 開始搜尋。
  • 非 RegExp 參數會隱式 new RegExp(),特殊字元需轉義。
  • 僅需布林判斷時,regexp.test(str) 效能優於 str.search(regexp) !== -1。

總結

search() 定位於「需正則模式且要取得首次位置」的輕量需求。單純存在性檢查請用 test(),固定子字串用 indexOf() 或 includes()。

copyright © 萬盛學電腦網 all rights reserved