關於 String.indexOf()
前言
最近發現 String 可以直接搜尋字串,在此做個紀錄。
內容
範例如下
const str = 'Blue Whale'; console.log( str.indexOf('Blue') ); console.log( str.indexOf('Blute') ); console.log( str.indexOf('Whale', 0) ); console.log( str.indexOf('Whale', 5) ); console.log( str.indexOf('Whale', 7) ); // 0 // -1 // 5 // 5 // -1
使用的方法很簡單,只需把要找的字串當引數即可,如範例的第一次與第二次的使用,回傳的結果是索引值,如果找不到會回傳"-1",第三次以後會輸入第二個引數,這第二個引數是指定從那個索引值開始找,可以把不輸入引數就是第二個引數輸入 0 的結果。
沒有留言:
張貼留言