JavaScript中的indexOf()方法是用来检索字符串中指定的字符或子字符串的位置,如果没有找到,则返回-1。它的用法如下:
var str = 'This is a string.'; var index = str.indexOf('is'); console.log(index); // 2
上面的代码中,indexOf()方法检索字符串“This is a string.”中的“is”,并返回2,表示从字符串的第二个位置开始出现“is”。
indexOf()方法也支持第二个参数,用于指定从哪个位置开始检索,例如:
var str = 'This is a string.'; var index = str.indexOf('is', 3); console.log(index); // 5
上面的代码中,indexOf()方法检索字符串“This is a string.”中的“is”,但从索引3的位置开始检索,并返回5,表示从字符串的第五个位置开始出现“is”。
indexOf()方法还支持第三个参数,用于指定检索的最大长度,例如:
var str = 'This is a string.'; var index = str.indexOf('is', 3, 6); console.log(index); // -1
上面的代码中,indexOf()方法检索字符串“This is a string.”中的“is”,但从索引3的位置开始检索,最多只检索6个字符,并返回-1,表示没有找到“is”。
indexOf()方法的用法为:
- str.indexOf(searchValue[, fromIndex]):检索字符串中指定的字符或子字符串的位置,并返回位置索引;
- searchValue:要检索的字符或子字符串;
- fromIndex:可选,从哪个位置开始检索;
- length:可选,检索的最大长度。