JavaScript 字符串模板
模板字面量使用反引号(``)而不是引号("")来定义字符串:
比如:
let text = `Hello World`;
使用模板字面量,可以在字符串中同时使用单引号与双引号:
let text = `He's often called "Johnny"`;
模板字面量还允许多行字符串:
let text = `The quick brown fox jumps over the lazy dog`;
模板字面量还允许字符串中的变量:
let firstName = "Tom"; let lastName = "Gates"; let text = `Welcome ${firstName },${lastName }`;
模板字面量还允许字符串中的表达式:
let price = 10; let VAT = 0.25; let total = `Total: ${(price * (1+ VAT)).toFixed(2)}`';
模板字面量还可以制作HTML模板
let header = "Templates"; let tags = ["template", "javascript", "es6"]; let html = `<h2>${header}</h2><ul>`; for(const x of tags) { html +=`<li>${x}</li>`; } html += `</ul>`;