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

瀏覽器相容性

另見