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 |
是 | 是 | 是 | 是 | 是 | 是 |