Sub topic 3
Multiline Strings and Their Whitespace
This chapter assumes you can write a basic template literal with backticks and ${}. It also assumes you know how \n works in single- and double-quoted strings and can use split, map, and join.
Line Breaks Are Part of the String
A regular string literal cannot span lines unless you write \n escapes. A template literal can. Every line break between the backticks becomes a newline character in the result, and so does every space or tab at the start of a line.
const text = `line one
line two`;
console.log(text.split("\n").length); // 2
console.log(JSON.stringify(text)); // "line one\n line two"JSON.stringify makes the hidden characters visible. The two spaces before line two are kept. JavaScript has no rule that strips "code indentation" from inside the backticks, so the string holds exactly the characters you typed.
Line endings are normalized. If the source file uses Windows line endings (\r\n) or old Mac line endings (\r), each line break in a template literal still becomes a single \n. The string therefore does not depend on the editor settings of whoever saved the file.
The Indentation Problem
Trouble starts when a template literal sits inside indented code. You usually want the code to look tidy, but the tidy layout leaks into the string:
function query() {
return `
SELECT id, name
FROM users
`;
}
console.log(JSON.stringify(query()));
// "\n SELECT id, name\n FROM users\n "That result has three kinds of unwanted whitespace:
- A leading
\n, because the content starts on the line after the opening backtick. - Four spaces of indentation on each content line.
- A trailing
\n, made of the last line break plus the indentation before the closing backtick.
SQL ignores this whitespace. Command-line output, emails, test snapshots, and Markdown do not.
Ways to Control Whitespace
Start and end on the content lines
The simplest fix is to put the content right next to the backticks and leave the continuation lines unindented:
function greeting(name) {
return `Hello, ${name}.
Your order has shipped.`;
}
console.log(greeting("Ada"));
// Hello, Ada.
// Your order has shipped.This gives an exact result but breaks the visual indentation of the function.
Trim the ends
trim() removes the leading and trailing whitespace, which fixes problems 1 and 3. It does not touch the indentation inside the string. Use it when only the first and last lines are the issue.
Join an array of lines
const message = [
"Hello, Ada.",
"Your order has shipped.",
].join("\n");This keeps your code indented and the output exact. The cost is that you give up the multiline syntax.
Write a dedent helper
A small function can remove the common indentation for you:
function dedent(text) {
const lines = text
.replace(/^\n/, "")
.replace(/\n\s*$/, "")
.split("\n");
const indent = Math.min(
...lines
.filter((line) => line.trim() !== "")
.map((line) => line.match(/^ */)[0].length)
);
return lines.map((line) => line.slice(indent)).join("\n");
}
function query() {
return dedent(`
SELECT id, name
FROM users
WHERE active = 1
`);
}
console.log(JSON.stringify(query()));
// "SELECT id, name\nFROM users\n WHERE active = 1"The helper finds the smallest indentation among the non-blank lines and removes that much from every line. Indentation beyond the minimum, such as the extra two spaces before WHERE, is kept. Libraries usually offer the same thing as a tag (` dedent... `), which a later chapter covers.
Continue a line with a backslash
A backslash right before a line break removes the line break. This lets you wrap a long single-line string in your source:
const msg = `This sentence is long enough to wrap, \
but it prints on one line.`;
console.log(msg);
// This sentence is long enough to wrap, but it prints on one line.Only the backslash and the line break are removed. Any spaces at the start of the next line stay in the string, so leave that line unindented.
Choosing an Approach
| Approach | Keeps code indented | Exact output | Best for |
|---|---|---|---|
| Content next to backticks | No | Yes | Short messages |
| `trim()` | Yes | Ends only | Whitespace-insensitive text |
| Array plus `join("\n")` | Yes | Yes | Line-by-line output |
| Dedent helper | Yes | Yes | Large blocks such as SQL or Markdown |
| Backslash continuation | Partly | Yes | Wrapping one long line |
Common Errors
- Snapshot tests fail on whitespace. The expected string has a trailing
\nthat came from indenting the closing backtick. - Assuming the
\rstays. Windows line endings in source code still give\n. If you need\r\nin the output, write the\r\nescapes yourself. - Indenting after a backslash continuation. The indentation becomes spaces in the middle of the sentence.
Exercise
Inside a function body indented by two spaces, you write ` return \n a\n b\n ; as real line breaks (opening backtick at the end of the return line, "a" indented 4 spaces, "b" indented 6, closing backtick indented 2). What does JSON.stringify show for the string, and what does the dedent` helper from this chapter return?
Show answer
The raw string is "\n a\n b\n ". The dedent helper strips the leading newline and the trailing "\n ", finds a minimum indentation of 4, and returns "a\n b".
Exercise
Why does ` one \ ` followed by a line break and then two ` (four leading spaces) print "one two" with five spaces instead of "one two"?
Show answer
The backslash continuation removes only the backslash and the line break. The space before the backslash and the four spaces of indentation on the next line remain, giving five spaces.