JavaScript模板文字指南

在ES2015(也稱為ES6)中引入的Template Literals提供了一種聲明字符串的新方法,同時還提供了一些已經廣受歡迎的有趣的新構造。

模板文字簡介

模板文字是ES2015 / ES6的一項新功能,與ES5及以下版本相比,它可讓您以新穎的方式處理字符串。

乍一看語法非常簡單,只需使用反引號而不是單引號或雙引號即可:

const a_string = `something`

它們之所以獨特,是因為它們提供了很多用引號構建的普通字符串所沒有的功能,尤其是:

  • 它們提供了定義多行字符串的絕佳語法
  • 它們提供了一種簡單的方法來對字符串中的變量和表達式進行插值
  • 它們允許您使用模板標籤創建DSL(DSL表示域特定的語言,例如,在React by Styled Components中使用,以為組件定義CSS)

讓我們詳細研究其中的每一個。

多行字符串

在ES6之前的版本中,要創建一個跨越兩行的字符串,您必須使用\行尾的字符:

const string =
  'first part \
second part'

這允許在兩行上創建一個字符串,但是僅在一行上呈現:

first part second part

要同時在多行上呈現字符串,您需要明確添加\n在每一行的末尾,如下所示:

const string =
  'first line\n \
second line'

或者

const string = 'first line\n' + 'second line'

模板文字使多行字符串更簡單。

使用反引號打開模板文字後,您只需按Enter即可創建新行,不包含任何特殊字符,並且按原樣呈現:

const string = `Hey
this

string
is awesome!`

請記住,空間是有意義的,因此請執行以下操作:

const string = `First
                Second`

將要創建一個像這樣的字符串:

First
                Second

an easy way to fix this problem is by having an empty first line, and appending the trim() method right after the closing backtick, which will eliminate any space before the first character:

const string = `
First
Second`.trim()

Interpolation

Template literals provide an easy way to interpolate variables and expressions into strings.

You do so by using the ${...} syntax:

const myVariable = 'test'
const string = `something ${myVariable}` //something test

inside the ${} you can add anything, even expressions:

const string = `something ${1 + 2 + 3}`
const string2 = `something ${doSomething() ? 'x' : 'y'}`

Template tags

Tagged templates is one feature that might sound less useful at first for you, but it’s actually used by lots of popular libraries around, like Styled Components or Apollo, the GraphQL client/server lib, so it’s essential to understand how it works.

In Styled Components template tags are used to define CSS strings:

const Button = styled.button`
  font-size: 1.5em;
  background-color: black;
  color: white;
`

In Apollo template tags are used to define a GraphQL query schema:

const query = gql`
  query {
    ...
  }
`

The styled.button and gql template tags highlighted in those examples are just functions:

function gql(literals, ...expressions) {}

this function returns a string, which can be the result of any kind of computation.

literals is an array containing the template literal content tokenized by the expressions interpolations.

expressions contains all the interpolations.

If we take an example above:

const string = `something ${1 + 2 + 3}`

literals is an array with two items. The first is something, the string until the first interpolation, and the second is an empty string, the space between the end of the first interpolation (we only have one) and the end of the string.

expressions in this case is an array with a single item, 6.

A more complex example is:

const string = `something
another ${'x'}
new line ${1 + 2 + 3}
test`

in this case literals is an array where the first item is:

;`something
another `

the second is:

;`
new line `

and the third is:

;`
test`

expressions in this case is an array with two items, x and 6.

The function that is passed those values can do anything with them, and this is the power of this kind feature.

The most simple example is replicating what the string interpolation does, by joining literals and expressions:

const interpolated = interpolate`I paid ${10}€`

and this is how interpolate works:

function interpolate(literals, ...expressions) {
  let string = ``
  for (const [i, val] of expressions.entries()) {
    string += literals[i] + val
  }
  string += literals[literals.length - 1]
  return string
}

More js tutorials: