Share via


indexOf 方法

更新:2007 年 11 月

傳回的字元位置是子字串首次出現在 String 物件中的位置。

 function indexOf(subString : String [, startIndex : Number]) : Number

引數

  • subString
    必要項。在 String 物件內搜尋的子字串。

  • startIndex
    選擇項。整數值,指定開始在 String 物件中搜尋的索引。如果省略,則會由字串之首開始搜尋。

備註

indexOf 方法會傳回整數值,表示子字串在 String 物件中的起始位置。如果找不到子字串,則傳回 -1。

如果 startindex 是負數,會將 startindex 視為零處理。如果此值大於最大的字元位置索引的話,則會將其視為最大可能索引。

搜尋是從左而右開始。否則這方法就與 lastIndexOf 無異。

範例

以下範例說明如何使用 indexOf 方法。

function IndexDemo(str2){
   var str1 = "BABEBIBOBUBABEBIBOBU"
   var s = str1.indexOf(str2);
   return(s);
}

需求

1 版

套用至︰

String 物件

請參閱

參考

lastIndexOf 方法