JavaScript 中的模板字符串是一种方便的字符串语法,允许你在字符串中嵌入表达式和变量。
模板字符串使用反引号 “ 作为字符串的定界符分隔的字面量。
模板字面量是用反引号(`)分隔的字面量,允许多行字符串、带嵌入表达式的字符串插值和一种叫带标签的模板的特殊结构。
参数
- string text:将成为模板字面量的一部分的字符串文本。几乎允许所有字符,包括换行符和其他空白字符。但是,除非使用了标签函数,否则无效的转义序列将导致语法错误。
- expression:要插入当前位置的表达式,其值被转换为字符串或传递给 tagFunction。
- tagFunction:如果指定,将使用模板字符串数组和替换表达式调用它,返回值将成为模板字面量的值。
实例
const name = 'Runoob';
const age = 30;
const message = `My name is ${name} and I'm ${age} years old.`;
let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
let header = "";
let tags = ["RUNOOB", "GOOGLE", "TAOBAO"];
let html = `${header}
`;
for (const x of tags) {
html += `- ${x}
`;
}
html += `
`;
const name = 'John';
const age = 31;
const job = 'Web Developer';
const city = 'Beijing';
function hello(){
return 'hello';
}
let str =`
Name:${name}
age:${age}
job:${job}
city:${city}
calc:${2+2}
function:${hello()}
sanmu: ${age >
30 ? 'over 30': 'under 30' }
`
console.log(str);