詳解ES6新增字符串擴張方法includes()、startsWith()、endsWith()
當有人問到用來確定一個字符串是否包含在另一個字符串中有哪些方法時,我們會不假思索回答道:indexOf方法。其實,ES6 又提供了三種新方法includes()、startsWith()、endsWith()
,也是比較好用的。
indexOf方法在這里就不多說了,大家都比較熟悉,意思就是:返回給定元素在數組中第一次出現的位置,返回結果是匹配開始的位置,如果沒有出現則返回-1。
下面詳細介紹ES6新增的這三種方法:
①includes()
:返回布爾值,表示是否找到了參數字符串。
如下所示:
let str = 'Hello world!'; let res1 = str.includes('Hello'); let res2 = str.includes('hi'); console.log(res1); // true console.log(res2); // false
結果:
②startsWith()
:返回布爾值,表示參數字符串是否在原字符串的頭部。
如下所示:
let str = 'Hello world!'; let res1 = str.startsWith('Hello'); let res2 = str.startsWith('world'); console.log(res1); // true console.log(res2); // false
結果:
③endsWith()
:返回布爾值,表示參數字符串是否在原字符串的尾部。
如下所示:
let str = 'Hello world!'; let res1 = str.endsWith('!'); let res2 = str.endsWith('d'); console.log(res1); // true console.log(res2); // false
結果:
這三個方法都支持第二個參數,表示看是搜索的位置。
let str = 'Hello World!' console.log(str.includes('World', 5)) // true 從索引5(包含索引5)開始搜索 console.log(str.includes('World', 7)) // false console.log(str.startsWith('lo', 3)) // true console.log(str.startsWith('H', 3)) // false console.log(str.endsWith('Hel', 3)) // true console.log(str.endsWith('d', 3)) // false
到此這篇關于詳解ES6新增字符串擴張方法includes()、startsWith()、endsWith()的文章就介紹到這了,更多相關ES6 includes() startsWith() endsWith()內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
至2023年最好用的兼容多瀏覽器的原生js復制函數copyText
因為后臺需要增加一些復制一些內容非表單中內容,那么下面這個函數就非常的好用了,其實也是利用了表單的數據權限比較容易突破,下面是具體的實現函數,大家可以拿走2023-05-05js調試工具console.log()方法查看js代碼的執(zhí)行情況
以往都是使用alert的方式查看js代碼的執(zhí)行情況,今天看到有朋友使用console.log函數打印輸出函數,變量,對象,下邊就console.log的使用情況進行記錄2014-08-08Javascript調試之console對象——你不知道的一些小技巧
這篇文章主要總結了console對象的一些有用的方法,非常不錯,具有參考借鑒價值,需要的朋友參考下吧2017-07-07