歡迎您光臨本站 註冊首頁

詳解ES6新增字串擴張方法includes()、startsWith()、endsWith()

←手機掃碼閱讀     qp18502452 @ 2020-05-13 , reply:0

這篇文章主要介紹了詳解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


[qp18502452 ] 詳解ES6新增字串擴張方法includes()、startsWith()、endsWith()已經有266次圍觀

http://coctec.com/docs/javascript/show-post-234245.html