JavaScript 从零计算位置。
0 是字符串中的第一个位置,1 是第二个,2 是第三个 ...
lastIndexOf()
方法返回指定文本在字符串中最后一次出现的索引:
实例
var str = "The full name of China is the People's Republic of China."; var pos = str.lastIndexOf("China");
如果未找到文本, indexOf()
和 lastIndexOf()
均返回 -1。
var str = "The full name of China is the People's Republic of China."; var pos = str.indexOf("USA");
indexOf和 lastindexOf , 两种方法都接受作为检索起始位置的第二个参数。
var str = "The full name of China is the People's Republic of China."; var pos = str.indexOf("China", 18);
lastIndexOf()
方法向后进行检索(从尾到头),这意味着:假如第二个参数是 50,则从位置 50 开始检索,直到字符串的起点。
实例
var str = "The full name of China is the People's Republic of China."; var pos = str.lastIndexOf("China", 50);
lastIndexOf()
方法向后搜索(从末尾到开头),意思是:如果第二个参数是 15
,则从位置 15 开始搜索,一直搜索到字符串的开头。
实例
let str = "Please locate where 'locate' occurs!"; str.lastIndexOf("locate", 15) // 返回 7
js中indexOf()
和 search()
这两个方法,相等吗?
它们接受相同的参数,并返回相同的值?
这两种方法并不相等。差别如下:
search()
方法不能接受第二个起始位置参数。indexOf()
方法不能采用强大的搜索值(正则表达式)
热门文章
-
js charAt()和 charCodeAt()方法的使用(js 查找字符串)
2023-10-09 09:46
-
js search() 方法搜索特定值的字符串且返回匹配的位置
2023-10-09 09:01
-
js indexOf()查找字符串中的字符串
2023-10-09 09:58