ES6基礎之——判斷字符串裏是否包含其餘字符串

在ES6裏面添加了一些字符串的方法:includes()、startsWith()、endsWith(),他們能夠很方便的判斷字符串裏是否包含其餘字符串;

 

includes():是否包含了參數字符串,返回布爾值
startsWith():參數字符串是否在原字符串的頭部,返回布爾值
endsWith():參數字符串是否在原字符串的尾部,返回布爾值

 

例子:
let dessert = 'cake',
drink = 'tea'
let breakfast =`今天的早餐是 ${dessert} 與 ${drink} !`;

console.log(breakfast.startsWith('今天')) //true
console.log(breakfast.endsWith('!')) //true
console.log(breakfast.includes('apple')) //false

 

這三個方法都支持第二個參數,表示開始搜索的位置。
console.log(breakfast.startsWith('今天',0)) //true
console.log(breakfast.endsWith('!',19)) //true
console.log(breakfast.includes('cake',5)) //true

 

注意:使用第二個參數時,endsWith的行爲與其餘兩個方法有所不一樣。它針對前n個字符,而其餘兩個方法針對從第n個位置直到字符串結束。
相關文章
相關標籤/搜索