當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JavaScript String lastIndexOf()用法及代碼示例

字符串 lastIndexOf() 方法

lastIndexOf() is method 是一個 String 方法,用於檢查給定字符串中是否存在子字符串。它從子字符串所在的字符串返回子字符串的最後一個索引。如果字符串中不存在子字符串 – 則返回 -1。

用法:

    String.lastIndexOf(substring, [offset]);

這裏,substring是要搜索的字符串的一部分,並且[offset]是我們要搜索子字符串的特定索引,它是一個可選參數,默認值為 0。

注意: 方法 lastIndexOf()在字符串中向後搜索,參見示例 - 我們傳遞了偏移量 15,它返回索引 0。

例:

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
<script>		
    var str = "Hello friends say Hello";
    
    var substr = "Hello";		
    var index = str.lastIndexOf(substr);
    if(index!=-1)
        document.write(substr + " found at " + index + " position.<br>");
    else
        document.write(substr + " does not exist in the " + str + ".<br>");

    substr = "Hi";
    index = str.lastIndexOf(substr);		
    if(index!=-1)
        document.write(substr + " found at " + index + " position.<br>");
    else
        document.write(substr + " does not exist in the " + str + ".<br>");
    
    //searching from a specific index
    substr = "Hello";
    index = str.lastIndexOf(substr,10);		
    if(index!=-1)
        document.write(substr + " found at " + index + " position.<br>");
    else
        document.write(substr + " does not exist in the " + str + ".<br>");		

    substr = "friends";
    index = str.lastIndexOf(substr,15);		
    if(index!=-1)
        document.write(substr + " found at " + index + " position.<br>");
    else
        document.write(substr + " does not exist in the " + str + ".<br>");					
</script>
</body>
</html>

輸出

Hello found at 18 position.
Hi does not exist in the Hello friends say Hello.
Hello found at 0 position.
friends found at 6 position.



相關用法


注:本文由純淨天空篩選整理自 String lastIndexOf() Method with Example in JavaScript。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。