首页 编程 正文

js indexOf()查找字符串中的字符串

2023-10-09 09:58 23
admin

indexOf() 方法返回字符串中指定文本首次出现的索引(位置):

实例

var str = "The full name of China is the People's Republic of China.";
var pos = str.indexOf("China");

lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引:具体见lastIndexOf() 

js String.indexOf()

indexOf() 方法返回指定文本在字符串中第一次出现(的位置)的索引:

实例

let str = "Please locate where 'locate' occurs!";
str.indexOf("locate")    // 返回 7

JavaScript 从零开始计算位置。

0 是字符串中的第一个位置,1 是第二个,2 是第三个 ......

如果未找到文本,indexOf() 返回 -1:

let str = "Please locate where 'locate' occurs , https://www.hao366.net!";
str.lastIndexOf("Bill")    // 返回 -1

接受第二个参数作为搜索的开始位置:

实例

let str = "Please locate where 'locate' occurs!";
str.indexOf("locate", 15)    // 返回 21