String.prototype.lastIndexOf()
lastIndexOf() 方法用于在 String 值中搜索指定的子字符串,并返回其最后一次出现的索引。它接受一个可选的起始位置,并返回指定子字符串在小于或等于指定位置的最后一个出现处的索引。
试一试
const paragraph = "I think Ruth's dog is cuter than your dog!";
const searchTerm = "dog";
console.log(
`Index of the last "${searchTerm}" is ${paragraph.lastIndexOf(searchTerm)}`,
);
// Expected output: "Index of the last "dog" is 38"
语法
lastIndexOf(searchString)
lastIndexOf(searchString, position)
参数
searchString-
要搜索的子字符串。所有值都会被强制转换为字符串,因此省略它或传递
undefined会导致lastIndexOf()搜索字符串"undefined",这通常不是您想要的。 position可选-
该方法返回指定子字符串在小于或等于
position的最后一个出现处的索引,position的默认值为Infinity。如果position大于调用字符串的长度,则该方法会搜索整个字符串。如果position小于0,则行为与0相同,即该方法只在索引0处查找指定的子字符串。-
'hello world hello'.lastIndexOf('world', 4)返回-1,因为虽然子字符串world出现在索引6处,但该位置不小于或等于4。 -
'hello world hello'.lastIndexOf('hello', 99)返回12,因为hello在小于或等于99的最后一个出现位置是12。 -
'hello world hello'.lastIndexOf('hello', 0)和'hello world hello'.lastIndexOf('hello', -5)都返回0,因为两者都会导致该方法只在索引0处查找hello。
-
返回值
找到 searchString 的最后一个出现处的索引,如果未找到则返回 -1。
描述
字符串是零索引的:字符串的第一个字符的索引是 0,最后一个字符的索引是字符串长度减 1。
"canal".lastIndexOf("a"); // returns 3
"canal".lastIndexOf("a", 2); // returns 1
"canal".lastIndexOf("a", 0); // returns -1
"canal".lastIndexOf("x"); // returns -1
"canal".lastIndexOf("c", -5); // returns 0
"canal".lastIndexOf("c", 0); // returns 0
"canal".lastIndexOf(""); // returns 5
"canal".lastIndexOf("", 2); // returns 2
区分大小写
lastIndexOf() 方法区分大小写。例如,以下表达式返回 -1
"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1
示例
使用 indexOf() 和 lastIndexOf()
以下示例在字符串 "Brave, Brave New World" 中使用 indexOf() 和 lastIndexOf() 来查找值。
const anyString = "Brave, Brave New World";
console.log(anyString.indexOf("Brave")); // 0
console.log(anyString.lastIndexOf("Brave")); // 7
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-string.prototype.lastindexof |
浏览器兼容性
加载中…