说到 模版字符串 (Template strings or Template literals), 咱们先来看看在ES5中,咱们遇到的问题:javascript
假设咱们须要拼接一段html字符串,常规的作法以下:html
var text = 'ES5 sucks!'; var html = '\ <div> \ <p>' + text + '</p>\ </div>'; console.log(html);
或者:java
var text = 'ES5 sucks!'; var html = [ '<div>', '<p>' + text + '</p>', '</div>' ].join(''); console.log(html);
写的很难受对不对?到了ES2015, 有了 模版字符串 后,事情就变得简单了。code
模版字符串,就是用 ` 和 ` 包裹起来的字符串, 如:htm
let html = ` <div> <p>ES5 sucks!</p> </div> `; console.log(html);
在其中,咱们还可使用 ${变量名}, 直接引用变量,而不用字符串拼接了,如:ip
let text = 'ES5 sucks!'; let html = ` <div> <p>${text}</p> </div> `; console.log(html);
若是不想其中的字符被转译,好比保留换行字符等,可使用 String.raw, 如:字符串
console.log(`我是\n两行`); console.log(String.raw`我是\n一行`);
输出:string
> 我是 > 两行 > 我是\n一行