JavaScript 中的 indexOf() 方法用于在字符串中查找子字符串的索引,返回第一个出现的索引,找不到返回 -1。语法:str.indexOf(searchValue, fromIndex);参数:str(字符串)、searchValue(子字符串)、fromIndex(起始索引);返回值:索引或 -1。

indexof 简介
JavaScript 中的 indexOf() 方法用于在字符串中查找指定子字符串的索引,如果找到则返回该索引,否则返回 -1。
详细说明:
- 语法:
<code class="js">str.indexOf(searchValue, fromIndex)</code>
-
str:要进行搜索的字符串。 -
searchValue:要查找的子字符串。 -
fromIndex(可选):开始搜索的索引位置。默认为 0(从字符串开头开始)。
- 返回值:
- 如果在字符串中找到
searchValue,则返回其第一个出现的索引。 - 如果找不到
searchValue,则返回 -1。
- 示例:
<code class="js">const myString = "Hello, world!";
// 在字符串中查找 "world" 的索引
const index = myString.indexOf("world");
// 输出索引值
console.log(index); // 7</code>- 可选参数
fromIndex:
-
fromIndex参数指定从哪一个索引位置开始搜索。 - 如果
fromIndex为正值,则从指定索引开始搜索。 - 如果
fromIndex为负值,则从字符串末尾开始搜索。 - 如果
fromIndex大于字符串长度,则返回 -1。
注意:
-
indexOf()方法是大小写敏感的,即 "A" 和 "a" 被视为不同的字符。 -
indexOf()不会搜索正则表达式,只能搜索子字符串。










