indexOf() 回傳子字串在字串中**第一次**出現的索引 (0 基礎);lastIndexOf() 回傳**最後一次**出現的索引。找不到回傳 -1。本文詳細說明語法、參數與實務技巧。
str.indexOf(searchString[, fromIndex])
str.lastIndexOf(searchString[, fromIndex])
const str = 'Hello world, welcome to the universe.';
console.log(str.indexOf('welcome')); // 13
console.log(str.indexOf('World')); // -1 (大小寫不同)
console.log(str.indexOf('o')); // 4 (第一個 'o')
console.log(str.lastIndexOf('o')); // 31 (最後一個 'o')
console.log(str.indexOf('o', 5)); // 8 (從索引 5 開始找)
console.log(str.lastIndexOf('o', 20)); // 18 (從索引 20 向前找)
function contains(str, substr) {
return str.indexOf(substr) !== -1;
}
// 或 ES6: str.includes(substr)
function countOccurrences(str, substr) {
if (!substr.length) return 0;
let count = 0, pos = str.indexOf(substr);
while (pos !== -1) {
count++;
pos = str.indexOf(substr, pos + 1);
}
return count;
}
console.log(countOccurrences('ababa', 'aba')); // 1 (不重疊)
console.log(countOccurrences('aaaa', 'aa')); // 2 (不重疊)
<!DOCTYPE html>
<html>
<body>
<p id="demo">點擊按鈕查找 "welcome" 位置</p>
<button onclick="findIndex()">查找</button>
<script>
function findIndex() {
const str = 'Hello world, welcome to the universe.';
const pos = str.indexOf('welcome');
document.getElementById('demo').innerHTML = `索引位置: ${pos}`;
}
</script>
</body>
</html>
| 方法 | 回傳值 | 支援正則 | ES 版本 | 適用場景 |
|---|---|---|---|---|
| indexOf | 索引 / -1 | 否 | ES1 | 需索引位置、舊環境相容 |
| lastIndexOf | 最後索引 / -1 | 否 | ES1 | 從後往前找 |
| includes | true / false | 否 | ES2016 | 只需判斷存在、語意最清晰 |
| search | 索引 / -1 | 是 | ES1 | 需正則模式匹配 |
| match | 陣列 / null | 是 | ES1 | 需提取群組或所有匹配 |
indexOf 效能最佳 (內部最佳化)。String.prototype.indexOf 原生實作,避免正則開銷。includes 內部同樣用 indexOf,語意更佳。function allIndexes(str, substr) {
const indexes = [];
let i = str.indexOf(substr);
while (i !== -1) {
indexes.push(i);
i = str.indexOf(substr, i + 1);
}
return indexes;
}
console.log(allIndexes('ababa', 'aba')); // [0]
indexOf() / lastIndexOf() 是字串定位的基石方法:語法簡單、效能極佳、瀏覽器相容性完美。現代專案單純判斷存在請用 includes(),需索引或從後搜尋則用本二者。記住「大小寫敏感」與「回傳 -1 表找不到」即可避開常見坑。