How do you create multi-line string literals in JavaScript using template literals? | A1Lab@FahadM to JavaScriptEnglish • 6 days ago

How do you create multi-line string literals in JavaScript using template literals?

message-square
0

To create a multi-line string literal in JavaScript using template literals, wrap your text in backticks (`) instead of single or double quotes and press Enter across lines. Unlike regular quotes, template literals preserve actual line breaks (\n) and indentation directly inside the string and allow ${expression} interpolation on any line.


1. Basic Multi-Line Strings and Interpolation

Any newline or expression inside backticks is kept literally as part of the string, making multi-line messages, SQL/query text, or formatted blocks easy to read without \n or + concatenation.

const user = "Zainab";
const itemsCount = 4;

const message = `Hello ${user},
You have ${itemsCount} items in your cart.
Proceed to checkout when ready.`;

console.log(message);
  • Actual newlines preserved: Line breaks inside backticks produce real newline characters in the resulting string.
  • Expressions on any line: Use ${...} inside any line to insert variables, computed values, or function calls.

2. Handling Indentation Cleanly

Because template literals preserve exact whitespace, indenting lines inside a function or block can add unwanted leading spaces to every line. You can trim or dedent lines cleanly with JavaScript string helpers or a tagged template function.

// Dedent helper: removes common leading indentation across lines
function dedent(strings, ...values) {
  const raw = strings.reduce((acc, str, idx) => {
    const val = idx < values.length ? String(values[idx]) : "";
    return acc + str + val;
  }, "");

  const lines = raw.split("\n");
  const nonEmptyLines = lines.filter((line) => line.trim().length > 0);
  const minIndent = nonEmptyLines.reduce((min, line) => {
    const match = line.match(/^[ \t]*/);
    const len = match ? match[0].length : 0;
    return Math.min(min, len);
  }, Infinity);

  const padToRemove = Number.isFinite(minIndent) ? minIndent : 0;
  return lines.map((line) => line.slice(padToRemove)).join("\n").trim();
}

function buildReport(serviceName, latencyMs) {
  return dedent`
    Service: ${serviceName}
    Status: Healthy
    Avg Latency: ${latencyMs} ms
  `;
}

console.log(buildReport("auth-api", 42));
  • Why indentation shows up: Everything between the opening and closing backticks—including spaces or tabs before text—is included verbatim.
  • Tagged templates (dedent): Custom tag functions let you normalize leading spaces while keeping ${...} expressions intact.

3. Common Traps to Avoid

  • Accidentally keeping extra leading spaces or a leading/trailing blank line: Starting right after an opening backtick on a new line adds a leading \n and any spaces on that line.
  • Using single (') or double (") quotes for multi-line text: Standard string literals throw a SyntaxError on unescaped line breaks unless you escape with \n or join strings.
  • Confusing template literals with regular strings when escaping backslashes: Inside a template literal, \\ still represents a single literal backslash character.

TL;DR: Wrap your text in backticks (`) and span multiple lines naturally—line breaks and ${...} expressions work out of the box, and you can use a dedent tag or .trim() when you don’t want leading spaces or extra blank lines.

Are you building multi-line messages/prompts, formatting indented blocks inside functions, or interpolating dynamic values/lists into the string?