1. 程式人生 > >ES6 模板字串

ES6 模板字串

 

ECMAScript 6 入門

作者:阮一峰

授權:署名-非商用許可證

http://es6.ruanyifeng.com/#docs/string#%E6%A8%A1%E6%9D%BF%E5%AD%97%E7%AC%A6%E4%B8%B2

模板字串(template string)是增強版的字串,用反引號(`)標識。它可以當作普通字串使用,也可以用來定義多行字串,或者在字串中嵌入變數。

// 普通字串
`In JavaScript '\n' is a line-feed.`

// 多行字串
`In JavaScript this is
 not legal.`

console.log(`string text line 1
string text line 2`);

// 字串中嵌入變數
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

上面程式碼中的模板字串,都是用反引號表示。如果在模板字串中需要使用反引號,則前面要用反斜槓轉義。

let greeting = `\`Yo\` World!`;

如果使用模板字串表示多行字串,所有的空格和縮排都會被保留在輸出之中。

$('#list').html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`);

上面程式碼中,所有模板字串的空格和換行,都是被保留的,比如<ul>標籤前面會有一個換行。如果你不想要這個換行,可以使用trim方法消除它。

$('#list').html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`.trim());

模板字串中嵌入變數,需要將變數名寫在${}之中。

function authorize(user, action) {
  if (!user.hasPrivilege(action)) {
    throw new Error(
      // 傳統寫法為
      // 'User '
      // + user.name
      // + ' is not authorized to do '
      // + action
      // + '.'
      `User ${user.name} is not authorized to do ${action}.`);
  }
}

大括號內部可以放入任意的 JavaScript 表示式,可以進行運算,以及引用物件屬性。

let x = 1;
let y = 2;

`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"

`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"

let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"

模板字串之中還能呼叫函式。

function fn() {
  return "Hello World";
}

`foo ${fn()} bar`
// foo Hello World bar

如果大括號中的值不是字串,將按照一般的規則轉為字串。比如,大括號中是一個物件,將預設呼叫物件的toString方法。

如果模板字串中的變數沒有宣告,將報錯。

// 變數place沒有宣告
let msg = `Hello, ${place}`;
// 報錯

由於模板字串的大括號內部,就是執行 JavaScript 程式碼,因此如果大括號內部是一個字串,將會原樣輸出。

`Hello ${'World'}`
// "Hello World"

模板字串甚至還能巢狀。