Sub topic 3
Multiline Strings and Their Whitespace
This chapter assumes you can already write a basic template literal with backticks and use ${} to insert a value. It also assumes you know how ordinary single- and double-quoted strings work, including the \n escape, and that you are comfortable with common array and string methods such as split, map, join, replace, and trim.
Template literals let you put real line breaks inside a string. That is convenient, but it comes with a rule you have to keep in mind. Every character between the backticks becomes part of the string. That includes the newline right after the opening backtick, the spaces you used to indent your code, and any trailing spaces on a line. Most bugs with multiline templates come from forgetting this rule. This chapter explains exactly what ends up in the string and how to control it.
Line breaks become newline characters
A single- or double-quoted string cannot span lines. If you press Enter inside one, you get a SyntaxError, so you have to write \n yourself. A template literal accepts the line break directly and stores it as a newline character ("\n", code point U+000A).
const quoted = "line one\nline two";
const template = `line one
line two`;
console.log(quoted === template); // true
console.log(template.length); // 17
console.log(template.split("\n")); // [ 'line one', 'line two' ]The two strings are identical. The template version is easier to read when the text is long, such as an email body, a SQL query, a help message, or a block of generated code.
You can still write \n inside a template literal. It means the same thing as in a quoted string, and you can mix the two forms freely:
const mixed = `a\nb
c`;
console.log(mixed.split("\n")); // [ 'a', 'b', 'c' ]Indentation is kept exactly
The template literal does not know which spaces you meant as code formatting and which you meant as content. It keeps all of them. This shows up most often when a template sits inside an indented function:
function helpText() {
return `
Usage: tool [options]
Options:
-h Show help
-v Show version
`;
}
console.log(JSON.stringify(helpText()));
// "\n Usage: tool [options]\n\n Options:\n -h Show help\n -v Show version\n "JSON.stringify makes the invisible characters visible, and it shows three separate problems:
- The string starts with
"\n"because the line break after the opening backtick counts. - Every content line starts with four extra spaces of code indentation.
- The string ends with
"\n ": the newline after the last line and the two spaces before the closing backtick.
Where each piece of whitespace comes from
None of these parts is removed automatically. If you don't want one of them, you have to avoid writing it or strip it out afterward.
Strategies for controlling whitespace
Start the content right after the backtick
The simplest fix is to put the text against the left margin:
function helpText() {
return `Usage: tool [options]
Options:
-h Show help
-v Show version`;
}
console.log(JSON.stringify(helpText()));
// "Usage: tool [options]\n\nOptions:\n -h Show help\n -v Show version"The output is correct, but the source looks out of place inside an indented function, and auto-formatters or teammates may "fix" the indentation without realizing they changed the string.
Trim the ends
If only the leading and trailing newlines bother you, trim() removes them. It does not touch indentation inside the text:
const message = `
Hello,
Thanks for signing up.
`.trim();
console.log(JSON.stringify(message)); // "Hello,\nThanks for signing up."trim() also strips the leading spaces of the first line and the trailing spaces of the last line. That is usually what you want, but keep it in mind if the first line is supposed to be indented.
Write a dedent function
To keep your source indented and still get clean output, remove the common indentation from every line. This step is usually called dedenting. The function below takes a string, so it works with any template literal:
function dedent(text) {
const lines = text
.replace(/^\n/, "") // drop the newline after the opening backtick
.replace(/\n[ \t]*$/, "") // drop the final newline and closing indentation
.split("\n");
const indents = lines
.filter(line => line.trim() !== "")
.map(line => line.match(/^[ \t]*/)[0].length);
const min = indents.length ? Math.min(...indents) : 0;
return lines.map(line => line.slice(min)).join("\n");
}
function buildQuery() {
return dedent(`
SELECT id, name
FROM users
WHERE active = 1
`);
}
console.log(JSON.stringify(buildQuery()));
// "SELECT id, name\nFROM users\n WHERE active = 1"The function finds the smallest indentation among the non-blank lines (4 here) and removes that many characters from the start of each line. Relative indentation survives, so the WHERE line keeps its two extra spaces. Blank lines are left out when the minimum is computed. Otherwise an empty line would make the minimum 0 and nothing would be removed.
Many libraries ship a dedent helper, and later in this tutorial you'll see how a tag function can do the same job without the extra parentheses. The logic stays the same.
Build from an array
When the lines come from data, or when you need full control, skip literal line breaks and join an array:
const lines = [
"Usage: tool [options]",
"",
"Options:",
" -h Show help",
" -v Show version",
];
const help = lines.join("\n");
console.log(help.split("\n").length); // 5This approach is more verbose. In exchange, every character in the result is visible in the source, and the code can be formatted any way you like.
Comparing the approaches
| Approach | Source stays indented | Leading/trailing newline handled | Relative indentation kept | Main risk |
|---|---|---|---|---|
| Content at left margin | No | Yes, if written carefully | Yes | Formatters or editors change the text |
| `.trim()` | Yes, but indentation stays in output | Yes | Yes, plus unwanted code indent | Only fixes the ends |
| `dedent()` helper | Yes | Yes | Yes | Mixed tabs and spaces |
| `array.join("\n")` | Yes | Yes | Yes | Verbose, easy to forget a line |
Line continuations: breaking a line without a newline
Sometimes you want to wrap a long line in your source and keep it as one line in the string. A backslash at the very end of a line is a line continuation. The backslash and the line break that follows it are both removed from the string value:
const sentence = `This sentence is long enough that \
we wrap it in the source code.`;
console.log(sentence);
// This sentence is long enough that we wrap it in the source code.
console.log(sentence.includes("\n")); // falseA line continuation removes only the backslash and the line break. Indentation on the next line stays in the string, so this version gets extra spaces:
const spaced = `first part \
second part`;
console.log(JSON.stringify(spaced)); // "first part second part"Line endings are normalized
Source files on Windows often use CRLF (\r\n) line endings, while macOS and Linux use LF (\n). If template literals kept the raw characters, the same code would produce different strings on different machines. To prevent that, JavaScript normalizes literal line breaks inside a template: both CRLF and a lone CR become a single LF.
The example below uses eval so that the template source really contains a CR LF pair. The outer double-quoted string turns \r\n into actual carriage-return and line-feed characters before the template is parsed:
const fromCRLF = eval("`a\r\nb`");
console.log(JSON.stringify(fromCRLF)); // "a\nb"
console.log(fromCRLF.length); // 3
const escaped = `a\r\nb`;
console.log(JSON.stringify(escaped)); // "a\r\nb"
console.log(escaped.length); // 4Normalization applies only to actual line breaks in the source. Escape sequences you type, such as \r\n, are kept as written. If a protocol needs CRLF, for example HTTP headers or some email formats, you have to write the escapes explicitly or convert the string afterward:
const body = `line one
line two`;
const crlf = body.replace(/\n/g, "\r\n");
console.log(JSON.stringify(crlf)); // "line one\r\nline two"Interpolated values don't inherit indentation
When an interpolated value contains newlines, its second and later lines start at column 0. The surrounding indentation applies only to the place where the ${} appears:
const items = "- apples\n- pears";
const report = `Shopping list:
${items}`;
console.log(report);
// Shopping list:
// - apples
// - pearsOnly the first item is indented. To indent the whole value, change the value itself before you insert it:
function indent(text, spaces) {
const pad = " ".repeat(spaces);
return text.split("\n").map(line => pad + line).join("\n");
}
const items = "- apples\n- pears";
const report = `Shopping list:
${indent(items, 2)}`;
console.log(report);
// Shopping list:
// - apples
// - pearsNotice that the ${} now sits at the left margin, because indent supplies all the padding. If you keep two spaces before ${ as well, the first line gets four.
Gotchas from tools and editors
Many tools treat whitespace as formatting, but inside a template literal it is data. Watch for these cases:
- Trailing whitespace trimming. Many editors remove trailing spaces when you save a file. Inside a template literal, that silently changes the string. If trailing spaces matter, for example a Markdown hard line break written as two spaces, write them as
\u0020or add them in code. - Re-indentation. Moving a template into a deeper block with your editor's indent command adds spaces to every line of the string. A
dedenthelper protects you from this. Strings written at the left margin do not. - Snapshot and equality tests. A test that compares a multiline template to expected output fails on a single extra space or a missing final newline. Use
JSON.stringifyin failure messages so the difference is visible. - Minifiers. Minifiers keep template contents as they are, so the indentation ships to production. For large embedded text, dedent it, or load it from a file instead.
Exercise
What does JSON.stringify(s) print for the following code, and what is s.length?
const s =
hi
;
Show answer
It prints "\n hi\n". The string holds the newline after the opening backtick, two spaces, "hi", and the newline before the closing backtick, so s.length is 6.
Exercise
A developer writes Total: \ with a space after the backslash, then continues on the next line with 42. They expected "Total: 42" but got something else. What went wrong?
Show answer
The backslash is followed by a space, so it escapes that space instead of starting a line continuation. The line break then remains a real newline. The result is "Total: \n42", with two spaces (one before the backslash, one escaped) followed by a newline. Removing the trailing space after the backslash fixes it.
Exercise
Using the dedent function from this chapter, what string does dedent(\n a\n\n b\n ) return? Write it as JSON.
Show answer
"a\n\n b". The leading "\n" and the trailing "\n " are removed. The non-blank lines have indentation 6 and 8, so the minimum is 6. Removing 6 characters gives "a", the blank line stays "", and "b" keeps 2 spaces.
Exercise
You need an HTTP request head whose lines end in CRLF. Why doesn't saving your source file with Windows line endings and writing the head as a multiline template literal work, and what should you do instead?
Show answer
Literal line breaks inside a template literal are normalized to LF, so CRLF in the source file becomes "\n" in the string. Write the \r\n escapes explicitly, or build the text with LF and convert it with .replace(/\n/g, "\r\n").