Whether you’re a beginner or an experienced developer, read on. This tutorial has everything you need to start creating multi-line strings with confidence in your code.
With Template Literals
A template literal is defined by using the backtick character (
`), and it allows you to use line breaks like this:
let myString = `It was many and many a year ago,
In a kingdom by the sea,
That a maiden there lived whom you may know
By the name of ANNABEL LEE;--`
Nine times out of ten, template literals will be the way to go. You can include variables and expressions within your multi-line string.
However, although template literals are supported by all modern browsers (see CanIUse.com for details), they’re not necessarily supported by older browser versions, and you will face backward compatibility issues if your code needs to have legacy browser support.
With Newline Characters
Simply add the newline character (
\n) where you want the line to break, and your string will be outputted as a multi-line string when it’s outputted to the user’s screen:
let myString = "It was many and many a year ago,\nIn a kingdom by the sea,\nThat a maiden there lived whom you may know\nBy the name of ANNABEL LEE;--"
Multi-line strings with newline characters have excellent legacy browser support. However, they are prone to human error.
With a Backslash
You can also create a multi-line string by adding the backslash character (
\), separated from adjacent characters by a whitespace, to the end of each line.
let myString = "It was many and many a year ago, \ In a kingdom by the sea, \ That a maiden there lived whom you may know \ By the name of ANNABEL LEE;--"
Like newline characters, backslashes are prone to human error — especially if the code ends up in another developer’s hands, and they remove the line breaks without knowing why you put them there in the first place. So comment on your code accordingly.
Whether you’re thinking of using template literals, newline characters, or the backslash, consider the use case and the support required for your particular project and only then make your final choice. If you’re still unsure, try out each method to determine which one works best for your needs.