JavaScript indexOf() 方法和 lastIndexOf() 方法


一,定義和用法

indexOf() 方法可返回某個指定的字符串值在字符串中首次出現的位置

lastIndexOf() 方法可返回一個指定的字符串值最后出現的位置,在一個字符串中的指定位置從后向前搜索。

語法

stringObject.indexOf(searchvalue,fromindex)
stringObject.lastIndexOf(searchvalue,fromindex)

indexOf() 方法

參數 描述
searchvalue 必需。規定需檢索的字符串值。
fromindex 可選的整數參數。規定在字符串中開始檢索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略該參數,則將從字符串的首字符開始檢索。

 lastIndexOf() 方法

參數 描述
searchvalue 必需。規定需檢索的字符串值。
fromindex 可選的整數參數。規定在字符串中開始檢索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略該參數,則將從字符串的最后一個字符處開始檢索。

 

返回值

lastIndexOf() 方法如果在 stringObject 中的 fromindex 位置之前存在 searchvalue,則返回的是出現的最后一個 searchvalue 的位置。

說明

 indexOf() 方法將從頭到尾地檢索字符串 stringObject,看它是否含有子串 searchvalue。開始檢索的位置在字符串的 fromindex 處或字符串的開頭(沒有指定 fromindex 時)。如果找到一個 searchvalue,則返回 searchvalue 的第一次出現的位置stringObject 中的字符位置是從 0 開始的

 lastIndexOf() 方法將從尾到頭地檢索字符串 stringObject,看它是否含有子串 searchvalue。開始檢索的位置在字符串的 fromindex 處或字符串的結尾(沒有指定 fromindex 時)。如果找到一個 searchvalue,則返回 searchvalue 的第一個字符在 stringObject 中的位置stringObject 中的字符位置是從 0 開始的

二,提示和注釋

注釋:indexOf() 方法和 lastIndexOf() 方法都對大小寫敏感!

如果要檢索的字符串值沒有出現,則該方法返回 -1。

實例1:

<html>
<body>

<script type="text/javascript">

var str="Hello world!"
document.write(str.indexOf("Hello") + "<br />")
document.write(str.indexOf("World") + "<br />")
document.write(str.indexOf("world"))

</script>

</body>
</html>

效果如下:

 實例2:

<html>
<body>

<script type="text/javascript">

var str="Hello world!"
document.write(str.lastIndexOf("Hello") + "<br />")
document.write(str.lastIndexOf("World") + "<br />")
document.write(str.lastIndexOf("world"))

</script>

</body>
</html>

效果如下:

 

(不知讀者是否會有疑問,為何二者的結果相同?在此啰嗦下,因為 lastIndexOf()方法雖然是從后往前搜索,但返回的位置是從前開始數數和計算的,所以結果如上。)

三,參閱

charCodeAt() 方法substring() 方法

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM