search() 執行正則搜尋,回傳第一個匹配的索引。找不到回傳 -1。類似 indexOf() 但支援正則,不支援全域搜尋(忽略 g 旗標)。
str.search(regexp)
-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>
| 方法 | 支援正則 | 回傳值 | 用途 |
|---|---|---|---|
search() | 是 | 索引 / -1 | 找位置、需正則模式 |
indexOf() | 否 | 索引 / -1 | 簡單子字串找位置、效能最好 |
test() | 是 | true/false | 僅檢查是否匹配、效能最好 |
match() | 是 | 陣列/null | 擷取匹配內容/群組 |
search() 忽略 g 旗標,永遠從索引 0 開始搜尋。new RegExp(),特殊字元需轉義。regexp.test(str) 效能優於 str.search(regexp) !== -1。search() 定位於「需正則模式且要取得首次位置」的輕量需求。單純存在性檢查請用 test(),固定子字串用 indexOf() 或 includes()。