1.includes()
返回布尔值,判断是否找到参数字符串
可以接收两个参数,第一个值为需要查找的参数,第二个值为索引,从该索引后开始查找参数
let str = "abcdefg"
console.log(str.includes("c",1)); //true
console.log(str.includes("c",3)); //false
console.log(str.includes("h")); //false
2.startsWith()
返回布尔值,判断参数字符串是否在原字符串的头部
也可以接收两个参数,性质与includes一致
let str = "abcdefg"
console.log(str.startsWith("a")); //true
console.log(str.startsWith("a",1)); //false
console.log(str.startsWith("b")); //false
3.endsWith()
返回布尔值,判断参数字符串是否在原字符串的尾部
let str = "abcdefg"
console.log(str.endsWith("g")); //true
console.log(str.endsWith("f",5)); //false
console.log(str.endsWith("f",6)); //true
4.repeat()
返回新的字符串,表示将字符串重复指定次数返回
let str1 = "abc"
console.log(str1.repeat(2)); //abcabc
还有一些特殊情况
//如果参数是小数,向下取整
console.log(str1.repeat(4.2)); //abcabcabcabc
//如果参数是 0 至 -1 之间的小数,会进行取整运算,0 至 -1 之间的小数取整得到 -0 ,等同于 repeat 零次
console.log(str1.repeat(-0.4)); //
//如果参数是 NaN,等同于 repeat 零次
console.log(str1.repeat(-0.4)); //
//如果参数是负数或者 Infinity
5.padStart()
返回新的字符串,表示用参数字符串从头部(左侧)补全原字符串
可以接收两个参数,第一个参数为指定原字符串的长度,第二个参数为用来补全的字符串
let str2 = "aaa"
console.log(str2.padStart(5,"p")); //ppaaa
//如果指定的长度小于或者等于原字符串的长度,则返回原字符串
console.log(str2.padStart(3,"p")); //aaa
6.padEnd()
返回新的字符串,表示用参数字符串从尾部(右侧)补全原字符串
let str2 = "aaa"
console.log(str2.padEnd(5,"p")); //aaapp
//若第一个值小于原字符串的长度,输出的则是原字符串
console.log(str2.padEnd(2,"p")); //aaa
//如果原字符串加上补全字符串长度大于指定长度,则截去超出位数的补全字符串
console.log(str2.padEnd(6,"ppppp")); //aaappp
7.模板字符串
模板字符串相当于加强版的字符串,用反引号 `,除了作为普通字符串,还可以用来定义多行字符串,还可以在字符串中加入变量和表达式
let str3 = `asdfgh`
console.log(str3); //asdfgh
变量名写在 ${} 中, ${} 中可以放入 JavaScript 表达式
let name = "zth";
let age = 20;
let info = `My Name is ${name},I am ${age+1} years old next year.`
console.log(info);