Skip to content

Instantly share code, notes, and snippets.

@MarcWang
Created March 4, 2016 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarcWang/c6c16105170b7eb52834 to your computer and use it in GitHub Desktop.
Save MarcWang/c6c16105170b7eb52834 to your computer and use it in GitHub Desktop.

ES6 - 字串樣板 (Template Strings)

NodeJS => ES6支援程度

  • shipping (開發完成並默認支持)
  • staged (開發完成,但必須使用--harmony參數)
  • in progress (開發中)

Multiline strings

不需要再使用\n來換行

ES5的寫法

console.log(`In JavaScript '\n' is a line-feed.`)

ES6的寫法

console.log(`In JavaScript this is
 not legal.`)

Expression interpolation

使用${expression}就可以快速組合在字串中

ES5的寫法

var name = "Mario",
    time = "today";
console.log('Hello ' + name + ', how are you ' + time + '?');

ES6的寫法

var name = "Mario",
    time = "today";
console.log(`Hello ${name}, how are you ${time}?`);

Tagged template literals

var a = 5;
var b = 10;
function tag(strings, ...values) {
    console.log(strings[0]);    // "Hello "
    console.log(strings[1]);    // " world "
    console.log(values[0]);     // 15
    console.log(values[1]);     // 50

    return "Yes";
}

tag `Hello ${ a + b } world ${ a * b }`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment