模板字符串是es6
新增字符串字面量形式,可以使用多行字符串和字符串插值功能。它使用``
来代替普通字符串中的用双引号和单引号。
多行字符串
如果是需要多行字符串,对于普通的字符串,需要嵌套一个换行符
const str = "hello\n" + "world"
使用模板字符串那就该咋写咋写
const str = `hello
world`
变量
如果在字符串中需要用到变量,在普通字符串中需要通过+
运算符来连接,看上去有些许的不连贯
const name = "sakurige"
const str = "my name is " + name
console.log(str) // my name is sakurige
而是模板字符串,直接就可以通过${}
来嵌套一个变量或者表达式
const name = "sakurige"
const str = `my name is ${name}`
console.log(str) // my name is sakurige
标签模板字符串
通过``
来调用一个函数,普通字符串作为函数的第一个参数(数组)传入,而其他使用${}
包裹的变量分别作为后边的参数传入
以
${}
作为分割,被割开的字符串会整合成第一个参数,也就是数组传入
function fn() {
const arr = arguments[0]
const name = arguments[1]
const thing = arguments[2]
console.log(arr, name, thing)
}
const name = "sakurige"
const thing = "study"
fn`hello ${name}, you should ${thing} now`