ES2015入門系列7-模版字符串

說到 模版字符串 (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一行
相關文章
相關標籤/搜索