模板字符串(template string)是传统的javascript字符串的加强版。用反引号 `` 标识。它可以当作普通字符串使用,也可以用来方便的处理多行字符串和在字符串中嵌入变量。
表达式插值
在JavaScript ES6之前,您将使用 + 运算符将字符串中的变量和表达式连接起来。
模板文字(模板字符串)允许您使用字符串或字符串形式的嵌入式表达式。它们包含在反引号``中。
const name = 'World';
console.log(`Hello ${name}!`);//Hello World!
注意:模板文字是在2015年引入的(也称为ECMAScript 6或ES6或ECMAScript 2015)。某些浏览器可能不支持模板文字的使用。
多行字符串
模板文字也使编写多行字符串变得容易。
// 使用 + 运算符
const message1 = 'This is a long message\n' +
'that spans across multiple lines\n' +
'in the code.'
console.log(message1)
使用模板文字,您可以替换
const message1 = `This is a long message
that spans across multiple lines
in the code.`
console.log(message1)
标记模板
标记的模板的写法类似于函数定义。但是,在调用文字时,您不传递括号()。
function tagExample(strings) {
return strings;
}
// 创建标记模板
const result = tagExample`Hello World`;
console.log(result);
常用语法
作为前端开发者避免不了根据后台数据的返回,组装html,渲染页面。
$('#result').append(
'There are <b>' + basket.count + '</b> ' +
'items in your basket, ' +
'<em>' + basket.onSale +
'</em> are on sale!'
);
有时候还要给标签加一些属性,写起来很不方便,es6提供了模板字符串的方法,简化了这一过程
$('#result').append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
所有模板字符串的空格和换行,都是被保留的,如果你不想要前后换行,可以使用trim方法消除它。
在{}你可以写任意JavaScript表达式,包括调用函数。如果变量没有声明,会报错,如果{}中是一个字符串,则原样返回。