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

來源:互聯網
上載者:User

標籤:

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

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

 

文法:

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

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

 

 

 

 

參數 描述
searchvalue 必需。規定需檢索的字串值。
fromindex

indexOf():可選的整數參數。規定在字串中開始檢索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略該參數,則將從字串的最後一個字元處開始檢索。

lastIndexOf() :可選的整數參數。規定在字串中開始檢索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略該參數,則將從字串的最後一個字元處開始檢索。

   說明

 

indexOf():

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

 

 

lastIndexOf() :

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

 傳回值

lastIndexOf():

如果在 stringObject 中的 fromindex 位置之前存在 searchvalue,則返回的是出現的最後一個 searchvalue 的位置。

 

indexOf()、lastIndexOf() 方法都對大小寫敏感!

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

執行個體:

 

indexOf():

 1 <script type="text/javascript"> 2  3  4  5 var str="Hello world!" 6  7 document.write(str.indexOf("Hello") + "<br />") 8  9 document.write(str.indexOf("World") + "<br />")10 11 document.write(str.indexOf("world"))12 13 14 15 </script>

 

以上代碼的輸出:

0-16

 



lastIndexOf() :

 1 <script type="text/javascript"> 2  3  4  5 var str="Hello world!" 6  7 document.write(str.lastIndexOf("Hello") + "<br />") 8  9 document.write(str.lastIndexOf("World") + "<br />")10 11 document.write(str.lastIndexOf("world"))12 13 14 15 </script>

 

以上代碼的輸出:

0-16

 

本文來自:http://www.w3cschool.cn

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.