JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to write a multiline string in JavaScript?

Multiline string is a string that span multiple lines. In JavaScript, you write multiline strings in three ways:

  1. Using template literals
  2. Using the + operator
  3. Using the backslash (\) operator

Create Multiline string using template literals

Template literals were introduced in ES6. They allow you to create multiline strings easily. All you have to do is enclose the multiline string in a pair of backticks (`).

let str = `This
is
a
Multiline
String.`;
console.log(str);

Output

"This
is
a
Multiline
String."

Create Multiline string using the + operator

The + operator is used to concatenate strings. While concatenating the strings, if you specify \n newline character, a multiline string gets created.

let str = 'This\n' +
'is\n' +
'a\n' +
'Multiline\n' +
'String.';
console.log(str);

Output

"This
is
a
Multiline
String."

Create Multiline string using the \ operator

In this method, you use the \ operator to write a multiline string. Here, you have to specify \n newline character; otherwise, when you display the string on the standard output, it will print the string in a single line.

let str = 'This\n \
is\n \
a\n \
Multiline\n \
String.';
console.log(str);

Output

"This
is
a
Multiline
String."

Recommended Posts