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
热门文章
-
js charAt()和 charCodeAt()方法的使用(js 查找字符串)
2023-10-09 09:46
-
js search() 方法搜索特定值的字符串且返回匹配的位置
2023-10-09 09:01
-
js lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引
2023-10-09 09:59