如何在 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 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告