How to create a multiline string in JavaScript
By Flavio Copes
Learn how to create a multiline string in JavaScript using template literals, the backtick-delimited strings added in ES6 that let text span several lines.
To create a multiline string in JavaScript, use a template literal: a string delimited by backticks. Any line break you type inside it becomes part of the string.
JavaScript never had a true good way to handle multiline strings, until 2015 when ES6 was introduced, along with template literals.
Template literals are strings delimited by backticks, instead of the normal single/double quote delimiter.
They have a unique feature: they allow multiline strings:
const multilineString = `A string
on multiple lines`
const anotherMultilineString = `Hey
this is cool
a multiline
st
r
i
n
g
!
`
What did we do before template literals?
With regular quotes, a literal line break in the source is a syntax error. So we concatenated strings, adding \n where the line should break:
const address = 'Via Roma 12\n' +
'33100 Udine\n' +
'Italy'
Another old trick was ending each line with a backslash, which continues the string on the next line. You still had to add \n yourself:
const address = 'Via Roma 12\n\
33100 Udine\n\
Italy'
Both work, but they’re noisy and easy to break. A stray space after the backslash is a syntax error. Template literals removed all of this.
Interpolation works too
Inside a template literal you can also embed values with ${}:
const name = 'Valentina'
const message = `Hi ${name},
thanks for signing up!`
The line break and the interpolated value both end up in the final string.
Watch the indentation
Here’s the one thing that trips people up. Everything between the backticks is part of the string, including the spaces you use to indent your code:
function welcome() {
const message = `Hi,
welcome aboard`
console.log(message)
}
This prints:
Hi,
welcome aboard
The second line carries the 4 spaces of indentation. The string doesn’t know or care about how your code is formatted.
The fix is to start continuation lines at column 0, even if it looks odd inside an indented function. .trim() can help too, but only for whitespace at the very start and end of the whole string. It does nothing for the indentation of lines in the middle.