JavaScript ความยาวของตัวแปร String indexOf()
- 上一頁 includes()
- หน้าต่อไป lastIndexOf()
- กลับไปยังเพจหน้าต้น คู่มืออ้างอิง JavaScript String
定義和用法
indexOf()
方法返回值在字符串中第一次出現的位置。
如果未找到該值,則 indexOf()
方法返回 -1
。
indexOf()
方法區分大小寫。
另請參考:
實例
例子 1
在字符串中搜索 "welcome":
let text = "Hello world, welcome to the universe."; let result = text.indexOf("welcome");
例子 2
在字符串中搜索 "welcome":
let text = "Hello world, welcome to the universe."; let result = text.indexOf("Welcome");
例子 3
找到 "e" 的第一個匹配項:
let text = "Hello world, welcome to the universe."; text.indexOf("e");
例子 4
從位置 5 開始查找 "e" 的第一個匹配項:
let text = "Hello world, welcome to the universe."; text.indexOf("e", 5);
例子 5
找到 "a" 的第一個匹配項:
let text = "Hello world, welcome to the universe."; text.indexOf("a");
語法
string.indexOf(substring, start)
參數
參數 | 描述 |
---|---|
substring | 必需。要搜索的字符串。 |
start | 可選。開始的位置(默認為 0)。 |
返回值
類型 | 描述 |
---|---|
數字 |
搜索值出現的第一次位置。 如果未找到子串,則返回 |
技術細節
返回值
如果在 string 中的 start 位置之後存在 substring,返回出現的第一次 substring 的位置。如果没有找到子串,則返回 -1
。
說明
String.indexOf()
方法從頭到尾檢索字符串 string,看它是否包含子串 substring。開始檢索的位置在字符串 string 的 start 處或 string 的開頭(沒有指定 start 參數時)。如果找到了一个 substring,那麼 String.indexOf()
將返回 substring 的的第一个字符在 string 中的位置。string 中的字符位置是从 0 开始的。如果在 string 中没有找到 substring,那麼 String.indexOf()
方法將返回 -1
。
String indexOf() 與 String search() 的區別
indexOf()
方法無法搜索正則表達式。
search()
不能采用起始位置參數。
瀏覽器支持
indexOf()
是 ECMAScript1 (ES1) 特性。
所有瀏覽器都完全支持 ES1 (JavaScript 1997):
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
- 上一頁 includes()
- หน้าต่อไป lastIndexOf()
- กลับไปยังเพจหน้าต้น คู่มืออ้างอิง JavaScript String