String.prototype.lastIndexOf()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

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"

语法

js
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。

js
"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

js
"Blue Whale, Killer Whale".lastIndexOf("blue"); // returns -1

示例

使用 indexOf() 和 lastIndexOf()

以下示例在字符串 "Brave, Brave New World" 中使用 indexOf()lastIndexOf() 来查找值。

js
const anyString = "Brave, Brave New World";

console.log(anyString.indexOf("Brave")); // 0
console.log(anyString.lastIndexOf("Brave")); // 7

规范

规范
ECMAScript® 2026 语言规范
# sec-string.prototype.lastindexof

浏览器兼容性

另见