JS中indexOf的用法

2022-04-13 00:42:07 字數 1115 閱讀 6352

string.indexof(char, [startindex], [count]):返回指定字元在原字串中的第乙個匹配項的索引。可指定字元開始檢索位置和指定長度的字元,若沒有找到該字元,則返回 -1。也可以判斷陣列中是否包含某個值。

示例1:查詢字串中某一字元從頭開始第一次出現的索引

var str = "hello world!"console.log(str.indexof("o")) //4

console.log(str.indexof("hello")) //0

console.log(str.indexof("world")) //-1

console.log(str.indexof("world")) //6

需要注意的是,當匹配到乙個字串時,會返回字串中第乙個字元的索引,如上例匹配word時,返回的是6。

示例2:查詢字串中某一字元從指定位置開始第一次出現的索引

var str = "hello world! wo shi ooo"console.log(str.indexof("o",8)) //14

有indexof,也就有lastindexof,它和indecof相反,是匹配字串最後一次出現的索引

var str = "hello world! wo shi oll"onsole.log(str.indexof("o")) //4

console.log(str.lastindexof("o")) //20

對應indexof和lastindexof,通常用在判斷字串中是否包含某個字元的情景中:

var str = "hello world! wo shi oll"console.log(str.indexof("world") == -1) //true

console.log(str.indexof("world") == -1) //false

示例3:判斷陣列中是否包含某個元素

const arr = [1,5,3,8,22]

console.log(arr.indexof(2))//不存在,返回-1

console.log(arr.indexof(8))//存在,返回索引3

js中indexOf的用法詳解

string.indexof 方法 char,startindex count 報告指定字元在此例項中的第乙個匹配項的索引。搜尋從指定字元位置開始,並檢查指定數量的字元位置。引數value 要查詢的 unicode 字元。對 value 的搜尋區分大小寫。startindex int32 可選項,搜...

JS中的indexOf方法

indexof 是js中內建的方法之一,它的功能大家都很熟悉 簡單來說就是得到資料的索引,對於正則不熟練的人,是個很不錯的方法。如果查詢到返回索引,反之返回 1 固定用法 因為indexof 在不同型別使用的時候可能有細節性的注意點 這裡我們對不同資料型別使用indexof的場景進行討論 其實就是s...

JS中的indexof 解釋

indexof 方法可返回某個指定的字串值在字串中首次出現的位置。stringobject.indexof searchvalue,fromindex 該方法將從頭到尾地檢索字串 stringobject,看它是否含有子串 searchvalue。開始檢索的位置在字串的 fromindex 處或字串...