模板字符串
- 反引号包裹
- 允许换行
- 可以通过 ${} 插入表达式,表达式的执行结果将会输出到对应位置
const msg = `hey, ${name} --- ${1 + 2} ---- ${Math.random()}`
console.log(msg)
带标签的模板字符串
模板字符串的标签就是一个特殊的函数, 使用这个标签就是调用这个函数
const name = 'tom'
const gender = false
function myTagFunc (strings, name, gender) {
// console.log(strings, name, gender)
// return '123'
const sex = gender ? 'man' : 'woman'
return strings[0] + name + strings[1] + sex + strings[2]
}
const result = myTagFunc`hey, ${name} is a ${gender}.`
console.log(result)
标签函数返回什么,使用该标签的模板字符串就显示什么
标签可以用来对模板字符串进行操作,控制其展示内容
字符串扩展方法
.includes()
检索字符串是否包含
const message = 'Error: foo is not defined.'
console.log( message.includes('foo') )
.startsWith()
检索字符串以什么开始
const message = 'Error: foo is not defined.'
console.log( message.startsWith('Error') )
.startsWith()
检索字符串以什么结尾
const message = 'Error: foo is not defined.'
console.log( message.startsWith('.') )