JavaScript 字串 indexOf()
示例
搜尋字串中的“welcome”
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("welcome");
自己動手試一試 »
搜尋字串中的“Welcome”
let text = "Hello world, welcome to the universe.";
let result = text.indexOf("Welcome");
自己動手試一試 »
查詢第一個出現的“e”
let text = "Hello world, welcome to the universe.";
text.indexOf("e");
自己動手試一試 »
查詢第一個出現的“e”,從位置 5 開始
let text = "Hello world, welcome to the universe.";
text.indexOf("e", 5);
自己動手試一試 »
查詢第一個出現的“a”
let text = "Hello world, welcome to the universe.";
text.indexOf("a");
自己動手試一試 »
描述
indexOf()
方法返回字串中某個值第一次出現的索引。
indexOf()
方法如果未找到該值,則返回 -1。
indexOf()
方法區分大小寫。
語法
string.indexOf(searchvalue, start)
引數
引數 | 描述 |
searchvalue | 必需。 要搜尋的字串。 |
start | 可選。 開始搜尋的位置(預設為 0)。 |
返回值
型別 | 描述 |
一個數字 | 搜尋值第一次出現的位置。 如果從未出現,則返回 -1。 |
區別
字串 indexOf() 和字串 search()
indexOf()
方法無法針對正則表示式進行搜尋。
search()
無法接受起始位置引數。
瀏覽器支援
indexOf()
是 ECMAScript1 (ES1) 的特性。
ES1 (JavaScript 1997) 在所有瀏覽器中都得到完全支援
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 是 |