JavaScript: 3 Ways to Create Multiline Strings

Updated: May 25, 2023 By: Wolf Post a comment

This practical, example-based article shows you three different ways to declare a multiline string in JavaScript.

Using template literals (ES6 and newer)

The main points of this approach are:

  • Use backticks (`) to define the string.
  • Break the string into multiple lines, each representing a separate line of text.
  • Preserve the line breaks within the string.

Example:

const multilineString = `This is line 1.
This is line 2.
This is line 3.`;

console.log(multilineString);

Output:

This is line 1.
This is line 2.
This is line 3.

This approach is simple and intuitive. It also allows for variable interpolation.

Example:

const siteName = 'Sling Academy';
const today = new Date();

const multilineString = `Welcome to ${siteName}!
Today is ${today.toDateString()}.
You are very wonderful and amazing person!`

console.log(multilineString);

Output:

Welcome to Sling Academy!
Today is Thu May 25 2023.
You are very wonderful and amazing person!

Using string concatenation (works with old JavaScript)

Below are the main points of this method:

  • Define an empty string variable.
  • Concatenate each line of the string using the plus (+) operator.
  • Optionally, add newline characters (\n) between each line.

Example:

var multilineString = 'This is line 1.' +
                      '\nThis is line 2.' +
                      '\nThis is line 3.';

console.log(multilineString);

Output:

This is line 1.
This is line 2.
This is line 3.

This technique is compatible with older versions of JavaScript and works with antiquated browsers like IE. However, its drawback is requiring manual concatenation and newline character addition, which can be tedious for large multiline strings.

Using the join() method (ES6 and above)

Long story short, this method can be summarized as follows:

  • Define an array with each element representing a separate line of text.
  • Use the join() method with a line break delimiter (\n) to concatenate the lines into a single string.

Example:

const multilineString = [
  'This is a multiline string.',
  'It is written on multiple lines.',
  'It looks nice.',
].join('\n');

console.log(multilineString);

Output:

This is a multiline string.
It is written on multiple lines.
It looks nice.

The advantage of this technique is that it allows for a more structured representation of the multiline string. In addition, line breaks can be easily customized. However, it requires creating an array and using the join() method, which can be slightly more complex than other approaches.

Final words

We’ve walked through a few distinct ways to declare multiline strings in JavaScript. In general, you should use the first approach. However, in some rare specific situations, the other ones can become really helpful.