在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個位置直到字符串結束。