📅  最后修改于: 2023-12-03 14:42:25.294000             🧑  作者: Mango
在 JavaScript 中,"indexOf" 方法是一个常用的用于查找字符串中指定字符或子串的方法。它的语法如下:
string.indexOf(searchValue[, fromIndex])
其中:
该方法会返回查找到的字符或子串的第一个出现位置的索引值。如果没有找到,则返回 -1。
以下是一些示例代码,用于演示如何使用 "indexOf" 方法。
const str = "Hello, world!";
const index = str.indexOf("world");
console.log(index); // 7
在这个示例中,我们定义了一个字符串 "Hello, world!",然后使用 "indexOf" 方法查找子串 "world" 的位置。由于该子串在第 7 个位置出现,因此变量 "index" 的值为 7。
const str = "Hello, world!";
const index = str.indexOf("WORLD");
console.log(index); // -1
这个示例与示例 1 相似,只不过查找的子串变成了大写的 "WORLD"。由于字符串中不存在大写的 "WORLD",因此 "indexOf" 方法返回了 -1。
const str = "The quick brown fox jumps over the lazy dog";
const sub = "fox";
let index = str.indexOf(sub);
while (index !== -1) {
console.log(`${sub} found at index ${index}`);
index = str.indexOf(sub, index + 1);
}
这个示例演示了如何使用 "indexOf" 方法查找字符串中所有出现的子串。我们将子串 "fox" 存储在变量 "sub" 中,然后在一个 while 循环中不断调用 "indexOf" 方法,直到该方法返回 -1。
在每次查找到目标子串后,我们将其位置打印出来,然后将 "indexOf" 方法的第二个参数设置为当前查找位置的下一个位置,以便继续查找后面的子串。
在使用 "indexOf" 方法时,需要注意以下几点: