欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2020年05月12日 10:21:53   作者:huangfuyk  
這篇文章主要介紹了詳解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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論