includes(), startsWith(), endsWith()
传统上,JavaScript只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中。ES6又提供了三种新方法
includes(str) : 判断是否包含指定的字符串
let str = 'huangjianfeng' console.log(str.includes('feng')) // true console.log(str.includes('feg')) // false
startsWith(str) : 判断是否以指定字符串开头
let str = 'huangjianfeng' console.log(str.startsWith('huang')) // true
endsWith(str) : 判断是否以指定字符串结尾
let str = 'huangjianfeng' console.log(str.endsWith('feng')) // true
var s = 'Hello world!'; // 这三个方法都支持第二个参数,表示开始搜索的位置 // 使用第二个参数n时,endsWith的行为与其他两个方法有所不同。它针对前n个字符, // 而其他两个方法针对从第n个位置直到字符串结束 console.log(s.startsWith('world', 6)); // true console.log(s.endsWith('Hello', 5)); // true console.log(s.includes('Hello', 6)); // false
repeat(count) : 重复指定次数
repeat方法返回一个新字符串,表示将原字符串重复n次
let str1 = 'a'; let str2 = 'hello'; console.log(str1.repeat(3)); //aaa console.log(str2.repeat(2)); //hellohello console.log(str2.repeat(0)); //结果什么都没有 console.log(str2.repeat(2.8)); //结果是:hellohello,参数如果是小数,会被取整 // 如果repeat的参数是负数或者Infinity,会报错 // console.log(str2.repeat(-2)); //RangeError: Invalid count value // console.log(str2.repeat(Infinity)); //RangeError: Invalid count value // 如果参数是0到-1之间的小数,则等同于0,这是因为会先进行取整运算。 // 0到-1之间的小数,取整以后等于-0,repeat视同为0。 // 参数NaN等同于0 console.log(str2.repeat(0.8)); console.log(str2.repeat(-0.8)); console.log(str2.repeat(NaN)); //如果repeat的参数是字符串,则会先转换成数字 console.log(str2.repeat('b')); //"" ,字符b不能转换成数字,Number('b')结果是NaN console.log(str2.repeat('3')); //hellohellohello console.log(Number('b'))
模板字符串
简化字符串的拼接——模板字符串必须用 `` 包含,变化的部分使用${xxx}定义
let obj = {user: 'huang', age: 34} console.log(`我的名字叫做${obj.user},我的年龄是:${obj.age}`) // 我的名字叫做huang,我的年龄是:34