indexOf 回傳子字串第一次出現的索引,找不到時回傳 -1。這個「-1 代表沒有」的慣例,是 JavaScript 字串操作裡最該記牢的一條。
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to locate where in the string a specified value occurs.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
上面會輸出 13,也就是 "welcome" 的起始位置。
"Hello world".indexOf("o"); // 4,回傳第一個出現位置
"Hello world".indexOf("o", 5); // 7,從索引 5 之後才開始找
"Hello world".indexOf("xyz"); // -1,找不到
// 判斷包含與否,請用這種寫法,可讀性遠勝於 !== -1
"Hello world".includes("world"); // true
第一,indexOf 是區分大小寫的,"Hello".indexOf("hello") 會回傳 -1。需要忽略大小寫時,先對兩邊都套 toLowerCase(),或改用正則表達式的 /hello/i.test(str)。
第二,索引是 0 起算,而且依 UTF-16 碼元計算,因此 emoji 這類字元會佔兩個位置。若你要的是「第幾個字」這種對使用者有意義的數字,別直接用 indexOf 的結果來顯示。
另外,indexOf 也同樣存在於陣列上([1,2,3].indexOf(2) 回傳 1),行為一致;ES2016 之後另有 includes 可用,差別在於 includes 能正確判斷 NaN。