Skip to content

Template Literals

Backtick 字符串使用变量 interpolation, multiline 文本, and tagged templates.

你将学到

  • 创建 template literals 使用 backticks
  • Interpolating 表达式使用 ${ ... }
  • 编写 multiline 字符串不使用 escape 序列
  • Nesting template literals for 复杂格式化
  • Tagged templates for 自定义字符串处理

概念讲解

Backtick Strings

A template literal is a string delimited by backticks instead of quotes. Template literals solve two pain points of traditional strings: they allow multiline text without \n escapes, and they allow expression interpolation with the ${ ... } syntax.

Interpolation

Place any JavaScript expression inside ${ } and it is evaluated and converted to a string. This replaces the old concatenation style ("Hello " + name + "!") with a far more readable form: `Hello ${name}!`. You can interpolate variables, arithmetic, function calls, and even nested template literals.

Multiline Strings

With template literals, line breaks in the source are preserved in the output. This is ideal for HTML templates, SQL queries, and any text that spans multiple lines. To suppress leading whitespace, use a tag function or the common .trim() trick on the whole literal.

Tagged Templates

A tagged template calls a function with the string parts and interpolated values as separate arguments. This lets you preprocess the string — escape HTML, localize text, or build DSLs. Libraries like styled-components use tagged templates heavily. The tag function receives an array of string fragments and the interpolated values as individual arguments.

When to Use Them

Template literals are the modern default for any string that combines text with variables or spans multiple lines. Reserve single and double quotes for short, static strings where interpolation is not needed. Remember that backticks inside a template literal must be escaped if they appear in the content.

示例代码

              const product = "Laptop";
const price = 999;
const qty = 2;

// Interpolation replaces concatenation
const receipt = `You bought ${qty} × ${product} for $${(price * qty).toFixed(2)}`;
console.log(receipt);

// Multiline HTML template
const card = `
  <div class="card">
    <h2>${product}</h2>
    <p>Price: $${price}</p>
  </div>
`.trim();
console.log(card);

// Nested template literals
const items = ["Apple", "Banana", "Cherry"];
const list = `Fruits:
${items.map((i) => `  - ${i}`).join("\n")}`;
console.log(list);

// Tagged template: escape HTML to prevent XSS
function escapeHtml(strings, ...values) {
  const escape = (s) =>
    String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  return strings.reduce((acc, str, i) => acc + str + escape(values[i] ?? ""), "");
}
const userInput = "<script>alert(1)</script>";
console.log(escapeHtml`Comment: ${userInput}`);
            

Shows interpolation 使用 toFixed, multiline HTML template trimmed, nested template literals 内部映射, and tagged template 那个 escapes HTML 到 prevent XSS.

动手试一试

  • HTML ↔ Markdown

    Template literals 经常构建 HTML — convert 之间 HTML and Markdown 这里.

  • 情况 Converter

    Transform interpolated 文本到 不同 naming 约定.

常见错误

错误写法

Forgetting 到 escape backticks 内部 template literal

正确做法

如果你的字符串内容包含 backtick, escape 它使用 backslash. Alternatively, use 字符串.raw or 不同 quoting 策略 for 内容.

错误写法

Interpolating 用户输入到 HTML 不使用 escaping

正确做法

从不 inject untrusted 数据到 HTML 通过 template literals directly. Use tagged template 那个 escapes HTML, or rely on 框架如 React 那个 escapes 通过默认.

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误