lastIndexOf() 方法返回指定值在调用该方法的字符串中最后出现的位置,如果没找到则返回 -1。从该字符串的后面向前查找,从 fromIndex 处开始。
str.lastIndexOf(searchValue[, fromIndex])
searchValuefromIndexstr.length。如果为负值,则被看作 0。如果 fromIndex > str.length,则 fromIndex 被看作 str.length。字符串中的字符被从左向右索引。首字符的索引(index)是 0,最后一个字符的索引是 stringName.length - 1。
"canal".lastIndexOf("a") // returns 3
"canal".lastIndexOf("a",2) // returns 1
"canal".lastIndexOf("a",0) // returns -1
"canal".lastIndexOf("x") // returns -1
lastIndexOf 方法区分大小写。例如,下面的表达式返回 -1:
"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1
indexOf 和 lastIndexOf下例使用 indexOf 和 lastIndexOf 方法来定位字符串 "Brave new world" 中的值。
var anyString = "Brave new world";
console.log("The index of the first w from the beginning is " + anyString.indexOf("w"));
// Displays 8
console.log("The index of the first w from the end is " + anyString.lastIndexOf("w"));
// Displays 10
console.log("The index of 'new' from the beginning is " + anyString.indexOf("new"));
// Displays 6
console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new"));
// Displays 6
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. |
| ECMAScript 5.1 (ECMA-262) String.prototype.lastIndexOf |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) String.prototype.lastIndexOf |
Standard |
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |