此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
String.prototype.lastIndexOf()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
String 的lastIndexOf() 方法搜索该字符串并返回指定子字符串最后一次出现的索引。它可以接受一个可选的起始位置参数,并返回指定子字符串在小于或等于指定数字的索引中的最后一次出现的位置。
In this article
尝试一下
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的位置中的最后一次出现的索引,默认为+Infinity。如果position大于调用字符串的长度,则该方法将搜索整个字符串。如果position小于0,则行为与0相同,即该方法只在索引0处查找指定的子字符串。'hello world hello'.lastIndexOf('world', 4)返回-1——因为虽然子字符串world在索引6处出现,但该位置不小于或等于4。'hello world hello'.lastIndexOf('hello', 99)返回12——因为小于或等于99的位置中,最后一次出现hello的位置是索引12。'hello world hello'.lastIndexOf('hello', 0)和'hello world hello'.lastIndexOf('hello', -5)都返回0——因为两者都导致该方法只在索引0处查找hello。
返回值
如果找到了searchString,则返回最后一次出现的索引,否则返回-1。
描述
字符串的索引从 0 开始:字符串第一个字符的索引为0,字符串最后一个字符的索引为字符串长度减 1。
"canal".lastIndexOf("a"); // 返回 3"canal".lastIndexOf("a", 2); // 返回 1"canal".lastIndexOf("a", 0); // 返回 -1"canal".lastIndexOf("x"); // 返回 -1"canal".lastIndexOf("c", -5); // 返回 0"canal".lastIndexOf("c", 0); // 返回 0"canal".lastIndexOf(""); // 返回 5"canal".lastIndexOf("", 2); // 返回 2区分大小写
lastIndexOf() 方法区分大小写。例如,以下表达式返回-1:
"Blue Whale, Killer Whale".lastIndexOf("blue"); // 返回 -1示例
>使用 indexOf() 和 lastIndexOf()
以下示例使用indexOf() 和lastIndexOf() 在字符串"Brave, Brave New World" 中查找值。
const anyString = "Brave, Brave New World";console.log(anyString.indexOf("Brave")); // 0console.log(anyString.lastIndexOf("Brave")); // 7规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-string.prototype.lastindexof> |