You can add a line break to your JavaScript strings, by using the \n
symbol or backticks.
Here’s how it’s done.
A newline character
The most straightforward way to add a new line to a string in JavaScript is by using a
newline character. It’s spelled at \n
.
const oneStringTwoLines = `Hello,\nWorld!`;
console.log(oneStringTwoLines);
First line ends right after the \n
character, and the second part of the string is
printed on a new line.
Hello,
World!
Backticks
When you use backticks to declare strings in JS, you can just press Enter to move to a new line. Line break will be added automatically.
const s = `this
string
takes
multiple
lines`;
console.log(s);
Here’s what you’ll see in the console.
this
string
takes
multiple
lines