ES6 - Template strings

刷题的时候遇到了这个新语法 - 模板字符串,记录一下用法。

是增强版的字符串,用反引号(`)标识。主要用法:

  1. 作为普通字符串使用

    1
    `string text`
  2. 定义多行字符串

    1
    2
    3
    4
    console.log(`string text line 1
    string text line 2`);
    // "string text line 1
    // string text line 2"
  3. 在字符串中嵌入变量

    1
    2
    let expression = "xxxx";
    `string text ${expression} string text`
  4. 标签模板 (tagged template)
    相当于一个模板函数,tag表示函数,整个表达式的返回值,就是tag函数处理模板字符串后的返回值。

    1
    2
    3
    4
    5
    6
    let a = 5;
    let b = 10;

    tag`Hello ${ a + b } world ${ a * b }`;
    // 等同于
    tag(['Hello ', ' world ', ''], 15, 50);

For more specific explanation:
MDN
阮一峰 (start from section 5)