user
How to write a multi-line string in JavaScript?
alphonsio

In JavaScript, you can write a multi-line string using one of the following methods:

1. Template Literals (Preferred Method)

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.`;

2. String Concatenation

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.";

3. Using Escape Character ()

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.";

4. Array and join() Method

You 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');

Example Output:

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.

Summary:

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.