如何在 JavaScript 中獲取字串中指定值的最後一次出現的索引?


在本教程中,我們將學習如何在 JavaScript 中獲取字串中指定值的最後一次出現的索引。

最後一次出現是指在給定字串中找到的搜尋專案的最後一個位置。它可以是單個字元,也可以是單詞。為了找到最後一次出現的索引,JavaScript 中有一個方法,即 `lastIndexOf()` 方法。

使用 `lastIndexOf()` 方法

此方法將搜尋整個字串並返回該值最後位置的索引。如果找不到該專案,則返回 -1。

`lastIndexOf()` 方法在此處區分大小寫,“A”和“a”被識別為不同的值。字串索引位置將從 0 開始,結束索引將是字串長度減 1。

語法

使用者可以按照以下語法在 JavaScript 中獲取字串中指定值的最後一次出現的索引。

string.lastIndexOf(searchItem,start);

在上文的語法中,使用者可以看到 `lastIndexOf()` 方法有兩個引數,第一個是搜尋的字串值,這是必需的;第二個引數是可選的,我們在這裡給出位置(預設值為字串長度)。

示例

在下面的示例中,我們建立一個字串變數“str”來儲存字串值。我們搜尋值“Learn”最後一次出現的索引。為了找到索引,我們使用 `lastIndexOf()` 方法。原始字串是“Learn for free and enjoy! Learn and share!”。

<html> <head> <title>JavaScript String lastIndexOf() Method</title> </head> <body> <h3> Getting the last index of an occurrence in an string</h3> <div id = "result1"> String:</div> <div id = "result2"> Search Value:</div> <div id = "result3"> Index:</div> <script> var str1 = new String("Learn for free and enjoy! Learn and share!"); document.getElementById("result1").innerHTML += str1; document.getElementById("result2").innerHTML += "Learn"; var index = str1.lastIndexOf("Learn"); document.getElementById("result3").innerHTML += index; </script> </body> </html>

在上面的示例中,我們在字串“Learn for free and enjoy! Learn and share!”中搜索“Learn”最後一次出現的索引。請注意,該字串有兩個“Learn”出現。您可以嘗試查詢單個字元最後一次出現的索引。

示例

在下面的示例中,我們使用了一個按鈕,“點選這裡”,並帶有 onclick 函式 `last_index()`。在函式內部,字串變數“str”和搜尋變數使用 prompt 方法從使用者那裡獲取輸入。然後 `lastIndexOf()` 方法將搜尋項作為引數,並應用於字串“str”。然後將索引返回給“index_element”變數。

<html> <body> <h3>Getting the last occurrence of a value in string from user input.</h3> <p>Click the below button to take user inputs</p> <button onclick = "last_index()"> Click Here</button> <p id = "result"></p> <script> function last_index() { let str = prompt("Please enter the string", "all for one and one for all"); let search = prompt("Enter the search value", "all"); let index_element = str.lastIndexOf(search); document.getElementById("result").innerHTML = "The last occurence of "" + search + "" in "" + str + "" is " + index_element; } </script> </body> </html>

正如使用者所看到的,點選“點選這裡”按鈕後,將呼叫 `last_index()` 函式,它會顯示一條警報訊息,提示輸入字串;然後,點選確定後,第二條警報訊息提示輸入搜尋值。輸入值後,我們將獲得搜尋值在字串中的索引位置。

在本教程中,我們討論了 `lastIndexOf()` 方法,用於查詢字串中指定值最後一次出現的索引。此方法查詢索引很簡單。

更新於:2022年10月20日

459 次檢視

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.