indexOf() 回傳子字串第一次出現的索引位置,找不到則回傳 -1。它是最基本、也最常被使用的字串搜尋方法。
<!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>
var str = "Hello world, welcome to the universe.";
str.indexOf("welcome"); // 13 第一次出現的位置
str.indexOf("o"); // 4
str.indexOf("o", 5); // 8 從索引 5 之後開始找
str.indexOf("xyz"); // -1 找不到
str.lastIndexOf("o"); // 從尾端往前找
因為「找不到」回傳 -1 而不是 0,判斷存在與否時要特別小心:
// 正確:明確比較
if (str.indexOf("welcome") !== -1) { /* 找到了 */ }
// 危險:少了 !== -1 變成永真,或誤寫成 indexOf(...) 直接當條件
if (str.indexOf("welcome")) { /* 找不到時是 -1,仍為真! */ }
ES6 之後,String.prototype.includes() 語意更清楚,也不會有 -1 的陷阱:
str.includes("welcome"); // true
str.startsWith("Hello"); // true
str.endsWith("universe."); // true
另外提醒 indexOf 是區分大小寫的。要忽略大小寫,先統一轉小寫再比對:str.toLowerCase().indexOf("Welcome".toLowerCase())。