模板字符串

发布于: 8/16/2022 阅读大约需要1分钟

模板字符串是ES6的新特性。

语法

`单行文本`

`多行文本
第二行`

const name = 'h'
`字符串插值${name}`

function tag(str, args){}

tag`字符串 ${experssion} 字符串`

带标签的模板字符串

即,可以使用函数解析模板字符串

标签函数第一个参数包含一个字符串值的数组,其余的参数与表达式相关,例如:

const name = 'a'

const age = 12

function html(strings, ...exp) {
  console.log({ strings, exp })
  return strings
}

console.log(html`This is ${name}: ${age} \n Hello World !`)

image.png
其中, strings 参数包含一个 raw 属性, 以供我们访问模板字符串的原始字符串(未经特殊字符替换)