模板字符串
传统的JavaScript语言,输出模板通常是这样写的。
const name = 'Jack';
const age = 18;
const sentence = name + ' is ' + age+ ' years old';
console.log(sentence);
上面这种写法相当繁琐不方便,ES6引入了模板字符串解决这个问题。
const name = 'Jack';
const age = 18;
const sentence = `${name} is ${age} years old`;
console.log(sentence);
嵌入变量
模板字符串中嵌入变量,需要将变量名写在${}
之中。如上面的例子。
嵌入Javascript表达式
大括号内部可以放入任意的JavaScript表达式,可以进行运算,以及引用对象属性。
const name = 'Jack';
const age = 18;
const sentence = `${name} is ${age*2} years old`;
console.log(sentence);
others:
var x = 1;
var y = 2;
`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"
`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"
var obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// 3
嵌入调用函数
模板字符串之中还能调用函数。
function fn() {
return "Hello World";
}
`foo ${fn()} bar`
判断字符串
如果大括号中的值不是字符串,将按照一般的规则转为字符串。比如,大括号中是一个对象,将默认调用对象的toString
方法。
如果模板字符串中的变量没有声明,将报错。
// 变量place没有声明
var msg = `Hello, ${place}`;
// 报错
由于模板字符串的大括号内部,就是执行JavaScript代码,因此如果大括号内部是一个字符串,将会原样输出。
`Hello ${'World'}`
// "Hello World"
嵌套模板字符串
模板字符串甚至还能嵌套。
const Jack = {
name : 'Jack',
date : '2019-10-19',
todos : [
{name : 'Reading', completed : false},
{name : 'Writing', completed : true},
{name : 'Watch movie', completed : false},
]
}
上面代码中,模板字符串的变量之中,又嵌入了另一个模板字符串,使用方法如下。
const template = `
<ul>
${Jack.todos.map(todo => `<li>${todo.name}</li>`).join('')}
</ul>
`
console.log(template);
调用网页方法显示内容:
const template = `
<ul>
${Jack.todos.map(todo => `
<li>
${todo.name} ${todo.completed ? ' √ ':' X '}
</li>`).join('')}
</ul>
`
console.log(template);
如果需要引用模板字符串本身,在需要时执行,可以像下面这样写。
// 写法一
let str = 'return ' + '`Hello ${name}!`';
let func = new Function('name', str);
func('Jack') // "Hello Jack!"
// 写法二
let str = '(name) => `Hello ${name}!`';
let func = eval.call(null, str);
func('Jack') // "Hello Jack!"
模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。
// 普通字符串
`In JavaScript '\n' is a line-feed.`
// 多行字符串
`In JavaScript this is
not legal.`
console.log(`string text line 1
string text line 2`);
// 字符串中嵌入变量
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
上面代码中的模板字符串,都是用反引号表示。如果在模板字符串中需要使用反引号,则前面要用反斜杠转义。
var greeting = `\`Yo\` World!`;
如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中。如果你不想要这个换行,空格,可以使用trim
方法消除它。
const template = [
'<div class = "first">',
'<p>Hello<p>',
'</div>'
].join('');
使用模板字符串:
const template = `
<div class = "first">
<p>Hello<p>
</div>
`;
使用trim()方法删除空格:
模板字符串参数
function demo(){
return 'hello';
}
const user = 'Jack';
const topic = 'Learn how to markdown'
const sentence = demo`${user} has completed the book ${topic}`;
console.log(sentence);
写这段代码的本意是将参数传进去并输出,类似于:
function demo(string,user,topic) // string 除参数以外的所有语句,后面两个为参数
使用ES6的剩余参数
function demo(string,...values){
debugger;
}
const user = 'Jack';
const topic = 'Learn how to markdown'
const sentence = demo`${user} has completed the book ${topic}`;
console.log(sentence);
然后调用模板字符串函数就可以执行:
function demo(strings,...values){
const highlighted = values.map(value => `<span class = "highlight">${value}</span>`);
let str = '';
strings.forEach((string,i) => str += `${string}${highlighted[i] || ''}`);
return str;
}
const user = 'Jack';
const topic = 'Learn how to markdown'
const sentence = demo`${user} has completed the book ${topic}`;
console.log(sentence);
添加样式:
.highlight{
padding:2px 5px;
background: aqua;
color: white;
}
将forEach改成reduce方法是同样的结果:
const highlighted = values.map(value => `<span class = "highlight">${value}</span>`);
return strings.reduce((prev,curr,i) => `${prev}${curr}${highlighted[i] || ''}`,'');