indexOf()函数是JavaScript中的一个字符串方法,用于查找字符串中指定子字符串的位置。它的语法如下:
string.indexOf(searchValue, startIndex)
其中,searchValue
参数表示要搜索的子字符串,startIndex
参数表示搜索的起始位置(可选,默认为0)。
这个函数返回搜索到的子字符串的第一个字符的索引值,如果未找到则返回-1。需要注意的是,索引值从0开始计数。
以下是一些示例:
var str = "Hello, world!";
console.log(str.indexOf("world")); // 输出:7
console.log(str.indexOf("o")); // 输出:4
console.log(str.indexOf("o", 5)); // 输出:8
console.log(str.indexOf("test")); // 输出:-1
在示例中,第一个indexOf()
函数检查字符串"world"在str
中的位置,返回值为7。第二个indexOf()
函数查找字符"o"在str
中的位置,返回值为4。第三个indexOf()
函数从索引5开始查找字符"o"在str
中的位置,返回值为8。最后一个indexOf()
函数查找字符串"test"在str
中的位置,但由于没有找到,返回值为-1。