indexOf()
方法用于在字符串中查找指定的子字符串,并返回其第一个匹配项的索引位置。如果找不到匹配项,则返回 -1。
语法如下:
indexOf(SearchValue, start)
searchValue
:要查找的子字符串。
start
(可选):从该索引位置开始搜索(默认从 0 开始)。
返回第一个匹配项的索引位置,如果没有找到,则返回 -1。
const str = "Hello world";
const index = str.indexOf("o"); // 返回 4
const str = "Hello world";
const index = str.indexOf("world"); // 返回 6
const str = "Hello world";
const index = str.indexOf("o", 4); // 从索引位置 4 开始查找,返回 7
const str = "Hello world";
const index = str.indexOf("z"); // 返回 -1
const str = "Hello world";
let index = str.indexOf("o");
while (index !== -1) {// 打印找到的索引console.log(index);// 更新索引以查找下一个匹配项index = str.indexOf("o", index + 1);
}
toLowerCase()
方法或
toUpperCase()
方法来忽略大小写:
const str = "Hello world";
const index = str.toLowerCase().indexOf("HELLO"); // 返回 0,忽略大小写
该方法在所有主流浏览器中得到广泛支持。
indexOf()
,因为它的时间复杂度为 O(n)。对于重复的搜索操作,可以使用正则表达式或字符串操作库。始终验证返回的索引是否大于或等于 0,以确保找到了匹配项。
厂长资源
本文地址:https://www.badfl.com/article/e8ba1e265e39d97ce657.html