var name = 'Shannon'
var text = `Hello, ${ name }!`
console.log(text)
// <- 'Hello, Shannon!'
模板字符串是支持任何表达式的。使用模板字符串,代码将更容易维护,你无须再手动连接字符串和JavaScript表达式了。
看下面插入日期的例子,是不是又直观又方便:
`The time and date is ${ new Date().toLocaleString() }.`
// <- 'the time and date is 8/26/2015, 3:15:20 PM'
表达式中还可以包含数学运算符:
`The result of 2+3 equals ${ 2 + 3 }`
// <- 'The result of 2+3 equals 5'
鉴于模板字符串本身也是JavaScript表达式,我们在模板字符串中还可以嵌套模板字符串;
`This template literal ${ `is ${ 'nested' }` }!`
// <- 'This template literal is nested!'
模板字符串的另外一个优点是支持多行字符串;
多行文本模板
在ES6之前,如果你想表现多行字符串,你需要使用转义,数组拼合,甚至使用使用注释符做复杂的hacks.如下所示:
var escaped =
'The first line\n\
A second line\n\
Then a third line'
var concatenated =
'The first line\n' `
'A second line\n' `
'Then a third line'
var joined = [
'The first line',
'A second line',
'Then a third line'
].join('\n')
应用ES6,这种处理就简单多了,模板字符串默认支持多行:
var multiline = `The first line A second line Then a third line`
当你需要返回的字符串基于html和数据生成,使用模板字符串是很简洁高效的,如下所示:
var book = {
title: 'Modular ES6',
excerpt: 'Here goes some properly sanitized HTML',
tags: ['es6', 'template-literals', 'es6-in-depth']
}
var html = `<article>
<header>
<h1>${ book.title }</h1>
</header>
<section>${ book.excerpt }</section>
<footer>
<ul>
${
book.tags
.map(tag => `<li>${ tag }</li>`)
.join('\n ')
}
</ul>
</footer>
</article>`
上述代码将得到下面这样的结果。空格得以保留,多个li也按我们的预期被合适的渲染:
<article> <header> <h1>Modular ES6</h1> </header> <section>Here goes some properly sanitized HTML</section> <footer> <ul> <li>es6</li> <li>template-literals</li> <li>es6-in-depth</li> </ul> </footer> </article>
不过有时候我们并不希望空格被保留,下例中我们在函数中使用包含缩进的模板字符串,我们希望结果没有缩进,但是实际的结果却有四格的缩进。
