一、基本介绍
在JavaScript中,indexOf函数是一种非常实用的字符串方法。这个方法可以用来查找一个字符串中是否包含另一个字符串,并返回被查找字符串的位置。
二、语法格式
string.indexOf(searchValue[, fromIndex])
其中,string代表要搜索的字符串,searchValue代表要查找的子字符串,fromIndex代表开始查找的位置,可选参数。
如果省略fromIndex,则默认从起始位置开始查找。如果fromIndex为负数,则表示倒数第n个字符开始查找。
三、用法举例
1. 查找字符串中某个字符的位置
var str = "hello world";
var index = str.indexOf("o");
console.log(index);
// output: 4
以上代码中,我们在字符串”hello world”中查找字符”o”的位置,返回的位置是4,即该字符在字符串中的第5个位置。
2. 查找字符串中的子字符串
var str = "hello world";
var subStr = "world";
var index = str.indexOf(subStr);
console.log(index);
// output: 6
以上代码中,我们在字符串”hello world”中查找子字符串”world”的位置,返回的位置是6,即该子字符串在字符串中的第7个位置。
3. 从指定位置开始查找
var str = "hello world";
var subStr = "l";
var index = str.indexOf(subStr, 4);
console.log(index);
// output: 9
以上代码中,我们在字符串”hello world”中查找字符”l”,并且指定从位置4开始查找,返回的位置是9,即该字符在字符串中的第10个位置。
4. 查找不存在的子字符串
var str = "hello world";
var subStr = "js";
var index = str.indexOf(subStr);
console.log(index);
// output: -1
以上代码中,我们在字符串”hello world”中查找子字符串”js”,由于不存在该子字符串,所以返回-1。
5. 从字符串末尾开始查找
var str = "hello world";
var subStr = "o";
var index = str.lastIndexOf(subStr);
console.log(index);
// output: 7
以上代码中,我们在字符串”hello world”中查找字符”o”,但是从字符串末尾开始查找,返回的位置是7,即该字符在字符串中的倒数第2个位置。
四、总结
indexOf函数在JavaScript中是一种非常常用的字符串方法,它可以快速查找字符串中是否包含某个子字符串,并返回被查找字符串的位置。除了indexOf函数外,还有lastIndexOf函数可以从字符串末尾开始查找子字符串。掌握这两个函数的用法,可以使我们更加高效地处理字符串。
原创文章,作者:QMFCK,如若转载,请注明出处:https://www.506064.com/n/325181.html