模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。
一.模板字符串
1.基本使用
-
使用反引号(`)做标识,可以定义多行字符串,在字符串中使用${}嵌入变量。在模板字符串中的任何变量最终都会变为String类型输出。
// 普通字符串 `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}?`
①.特点-与传统输出模板相比
-
传统的 JavaScript 语言,输出模板。
$('#result').append( 'There are <b>' + basket.count + '</b> ' + 'items in your basket, ' + '<em>' + basket.onSale + '</em> are on sale!' );
-
使用模板字符串。
$('#result').append(` There are <b>${basket.count}</b> items in your basket, <em>${basket.onSale}</em> are on sale! `);
②.特点-模板字符串中使用反引号
-
若在模板字符串中需要使用到反引号,则前面要用反斜杠转义。
let greeting = `\`Yo\` World!`;
③.特点-输出多行字符串
-
如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中。
$('#list').html(` <ul> <li>first</li> <li>second</li> </ul> `);
④.特点-在${}中调用表达式,调用函数,嵌入变量
-
模板字符串中嵌入变量,需要将变量名写在${}之中。
function authorize(user, action) { if (!user.hasPrivilege(action)) { throw new Error( // 传统写法为 // 'User ' // + user.name // + ' is not authorized to do ' // + action // + '.' `User ${user.name} is not authorized to do ${action}.`); } }
-
大括号内部可以放入任意的 JavaScript 表达式,可以进行运算,以及引用对象以及对象属性。若引用的是对象则会调用对象的toString方法。
let x = 1; let y = 2; `${x} + ${y} = ${x + y}` // "1 + 2 = 3" `${x} + ${y * 2} = ${x + y * 2}` // "1 + 4 = 5" let obj = {x: 1, y: 2}; `${obj.x + obj.y}` // "3"
-
模板字符串之中还能调用函数。
//字符串中调用函数 function fn() { return "Hello World"; } `foo ${fn()} bar` // foo Hello World bar //引用模板字符串本身,在需要时执行,可以写成函数。 let func = (name) => `Hello ${name}!`; func('Jack') // "Hello Jack!" //同如下范例 let func = function (name) { return `Hello ${name}!`; } console.log(func('guys!'))
-
大括号内部是一个字符串,将会原样输出;变量没有声明就会报错。
`Hello ${'World'}` // "Hello World" // 变量place没有声明 let msg = `Hello, ${place}`; // 报错
⑤.特点-模板字符串嵌套
-
模板字符串嵌套使用。
const tmpl = addrs => ` <table> ${addrs.map(addr => ` <tr><td>${addr.first}</td></tr> <tr><td>${addr.last}</td></tr> `).join('')} </table> `; //调用 const data = [ { first: '<Jane>', last: 'Bond' }, { first: 'Lars', last: '<Croft>' }, ]; console.log(tmpl(data)); // <table> // // <tr><td><Jane></td></tr> // <tr><td>Bond</td></tr> // // <tr><td>Lars</td></tr> // <tr><td><Croft></td></tr> // // </table>