lastIndexOf() 會從右向左搜尋,回傳指定字串在整個字串中最後一次出現的索引值,語法如下:
str_object.lastIndexOf( search, start )
參數說明:
| 參數 | 說明 |
|---|---|
| str_object | 要處理的字串物件 |
| search | 必要。要搜尋的字串 |
| start | 選填。指定搜尋的起點;省略時從字串結尾開始往回找 |
提醒:字串索引從 0 開始計算。
<script language="JavaScript">
var str = "www.jb51.net";
document.write( str.lastIndexOf( "." ) + "<br />" );
document.write( str.lastIndexOf( ".", 5 ) + "<br />" );
document.write( str.lastIndexOf( ".", 10 ) );
</script>
執行後輸出:
9
3
9
第二個例子值得留意:起點設為 5 時,實際找到的是索引 3 的那個點符號,也就是搜尋範圍被限制在 www.5 這個區間內。這裡的 start 代表「搜尋的起始位置」,往左回頭找,而不是「搜尋的結束位置」。
實務上最常見的應用是取得副檔名或最後一段路徑,例如 str.lastIndexOf(".") 搭配 slice 取出檔名,或是 str.lastIndexOf("/") 取出目錄部分。