不要将模板字符串与模板引擎混淆,是两回事,或者说模板字符串是将以往的格式化字符串以一种语法来实现了。模板字符串需要使用反勾号(backtick, `)
支持字符串元素注入
const str = "str"
const num = 1
const void0 = void(0)
const bool = true
const obj = {foo: 'bar'}
const arr = [1, 2, 3]
const err = new Error('error')
const regexp = /foobar/
const str1 = `String: ${str}` //=> String: str
const str2 = `Number: ${num}` //=> Number: 1
const str3 = `null: ${null}` //=> null: null
const str4 = `undefined: ${void0}` //=> undefined: undefined
const str5 = `Boolean: ${bool}` //=> Boolean: true
const str6 = `Object: ${obj}` //=> Object: [object object]
const str7 = `Array: ${arr}` //=> Array: 1,2,3
const str8 = `Error: ${err}` //=> Error: Error: error
const str9 = `RegExp: ${regexp}` //=> RegExp: /foobar/
支持换行
const sql = `
SELECT * FROM Users
WHERE FirstName = 'Mike'
LIMIT 5;
`
再看一个例子:
const str = `A
B
C
D` //=> A\nB\nC\nD
console.log(str.length) //=> 7
多行模板字符串会在每一行的后面添加一个\n换行符,因此每一行的长度会加1。
多行字符串没有两种以上的定义语法,因此无法像下面第一行代码那样使用双引号嵌套单引号来表达字符串中的字符串:
const str1 = "Here is the outter string. 'This is a string in another string'"
但可以使用反斜杠来讲需要显示的反勾号转义为普通的字符串
const str2 = `Here is the outter string. \`This is a string in another string\``
网友评论