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 |
瀏覽器相容性
載入中…