支持换行
ES6新增了模板字面量定义字符串的能力,模版字面量保留了换行符,可以跨行定义字符串
const str1 = 'first line\nsecond line'
const str2 = `first line
second line`
console.log(str1)
// first line
// second line
console.log(str2)
// first line
// second line
console.log(str1 === str2)
// true
所以模板字面量在定义html时字符串时特别有用
const pageHtml = `
<html>
<head></head>
<body>
<div>111</div>
</body>
</html>
`
支持插值
模板字面量最常用的特性就是支持字符串插值,技术上讲,模板字面量不是字符串,而是一种特殊的javascript句法表达式,只不过求值之后得到的是字符串。
const a = 'world'
console.log(`hello ${a}`)
// hellp world
所有插入的值都会使用toString()强制转化为字符串
const a = { toString: () => 'world' }
console.log(`hello ${a}`)
// hello world
插值可以调用函数
const a = 'world'
console.log(`hello ${a.slice(0, 1)}`)
// hello w
模板字面量标签函数
const fn = (strings, expression1, expression2) => {
console.log('strings', strings)
console.log('expression1', expression1)
console.log('expression2', expression2)
return 'result'
}
const a = 'hello'
const b = 'world'
const res = fn`aaa${a}bbb${b}ccc`
console.log('res', res)
// strings ['aaa', 'bbb', 'ccc']
// expression1 hello
// expression2 world
// res result
fn``的形式称之为标签函数 第一个参数是获取插值前后的字符串的数组 后面的参数,就是一个一个插值
这样我们就可以自定义一个模板字面量的返回值了例子中的result
原始字符串
我们打印的一个换行符
console.log('\n')
会在控制台看到一个换行,而不是\n
但我们利用内置的标签函数
console.log(String.raw`\n`)
// \n
就能在控制台输出\n
标签函数接收的一个参数的实参是一个数组,它也有raw属性
const fn = (strings, expression1, expression2) => {
console.log('strings.raw', strings.raw)
}
const a = 'hello'
const b = 'world'
fn`\n${a}\u00A9${b}\u00A9`
// ['\\n', '\\u00A9', '\\u00A9']