How to Create Multiline Strings in JavaScript

To create multiline strings in JavaScript, you can use the “ES6 template literals”“+ operator”, or “Array.prototype.join()” function.

Method 1: Using ES6 template literals (enclosed by backticks)

The most efficient and recommended way to create multiline strings in JavaScript is to use the “ES6 template literals”, enclosed by backticks (`). It allows multiline strings without using escape sequences or concatenation.

Example

const multilineStr = `Harry Potter
web series is just announced
by HBO MAX`;

console.log(multilineStr);

Output

Harry Potter
web series is just announced
by HBO MAX

Method 2: Using + operator with newline escape sequence \n

This method involves breaking the string into multiple lines using the newline escape sequence “\n” and concatenating them using the “+ operator”.

Example

const multilineStr = "Harry Potter\n" +
"web series is just announced\n" +
"by HBO MAX";

console.log(multilineStr);

Output

Harry Potter
web series is just announced
by HBO MAX

Method 3: Using an array and the Array.prototype.join()

The Array.prototype.join() method involves creating an array of strings (each representing a line) and then joining them using the join() method with the newline separator \n.

Example

const multilineStr = ['This is a line',
'And this is another line',
'Finally, this is the third line'].join('\n');

console.log(multilineStr)

Output

This is a line
And this is another line
Finally, this is the third line

That’s it.

Leave a Comment