传统的JavaScript语言,输出模板通常是这样的写的。
1 2 3 4 5 6 | $( '#result' ).append( 'There are <b>' + basket.count + '</b> ' + 'items in your basket, ' + '<em>' + basket.onSale + '</em> are on sale!' ); |
上面这种写法相当繁琐不方便,ES6 引入了模板字符串解决这个问题。
1 2 3 4 5 | $( '#result' ).append(` There are <b>${basket.count}< / b> items in your basket, <em>${basket.onSale}< / em> are on sale! `); |
模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量
1 2 3 4 5 6 7 8 9 10 11 12 13 | // 普通字符串 `In JavaScript '\n' is a line-feed.` // 多行字符串 `In JavaScript this is not legal.` console.log(`string text line 1 string text line 2`); // 字符串中嵌入变量 let name = "Bob" , time = "today" ; `Hello ${name}, how are you ${time}? |
上面代码中的模板字符串,都是用反引号表示。如果在模板字符串中需要使用反引号,则前面要用反斜杠转义。
1 | let greeting = `\`Yo\` World!`; |
输入结果:`Yo` World!
如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中。
1 2 3 4 5 6 | $( '#list' ).html(` <ul> <li>first< / li> <li>second< / li> < / ul> `); |