模版字符串
模版字符串字面量 Template literals
用反引号创建
const str = `this is string`;
插值表达式
可以将变量插入到字符串内
const name = "Tom";
//$()内放变量或任何符合规则的语句,只要有返回值就会将内容嵌套在字符串中
const str1 = `hi,${name},$
{1+1},${Math.random()}`;
//打印出 hi,Tom,2,0.847285191160535
模板字符串标签函数 Tagged templates
const name = "zs";
const gender = true;
function myTagFunc(strings, name,
gender) {
//如果gender 为true 是男,false 是女
const sex = gender ? "man" : "woman";
// strings里面存的就是数组
return strings[0] + name +
strings[1] + sex + strings[2];
}
// 传进去的字符串被转化成数组,name 和gender也可以被传入
const str = myTagFunc `hi,${name} is a ${gender}`;
//打印出 hi,zs is a man
console.log(str);
字符串的扩展方法
- includes():是否包括()
- startsWith():是否以()开头
const str1 = "Error: foo is not defined";
// 字符串打点调用,判断是否以括号内的开头,返回值true或false
console.log(str1.startsWith("Error"));
- endsWith():是否以()结尾