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个位置直到字符串结束。
原文地址:https://www.cnblogs.com/fe-cherrydlh/p/11021086.html