In JavaScript, you can write a multi-line string using one of the following methods:
Template literals, introduced in ES6, allow you to create multi-line strings easily. They are enclosed by backticks ( ` ... ` ) and can span multiple lines.
const multiLineString = `This is a string
that spans multiple
lines.`;
You can use the +
operator to concatenate strings, including breaking them across multiple lines.
const multiLineString = "This is a string\n" +
"that spans multiple\n" +
"lines.";
You can use the backslash \
at the end of each line to indicate that the string continues on the next line.
const multiLineString = "This is a string \
that spans multiple \
lines.";
join()
MethodYou can also create an array of strings and then join them with a newline character.
const multiLineString = [
"This is a string",
"that spans multiple",
"lines."
].join('\n');
All the above methods will create the same multi-line string output. For example:
console.log(multiLineString);
Output:
This is a string
that spans multiple
lines.
The most common and preferred way in modern JavaScript is to use template literals (backticks), as they are easy to read and do not require additional characters for multi-line strings.