Creating a Multiline String in JavaScript

To create a multiline JavaScript string, you can enclose the string in template literals `. These multiline strings may contain newlines (\n), tab characters (\t), and other special characters. In addition to creating multiline strings, template string literals provide other useful features, such as string interpolation. Alternatively, you can build a multi-line string using the concatenation (+) operator. Template string literals make code more readable and eliminate the need for string concatenation or character escapes. In this JavaScript example, we use template string literals to create a multi-line string containing HTML tags, tabs, and line breaks. Click Execute to run the JavaScript Multiline String example online and see the result. More JavaScript multiline string examples are provided below.
Creating a Multiline String in JavaScript Execute
let str = `<div>
	<p>JavaScript Multiline String 1</p>
	<p>JavaScript Multiline String 2</p>
</div>`;

console.log(str);
Updated: Viewed: 8802 times

Creating a multiline string using the newline character

Before ECMAScript 6 (ES6), newlines and string concatenation broke a string into multiple lines. Newlines are part of a string. The newline character is denoted by "\n". We can use this character to stretch our string across multiple lines.

JavaScript Multiline String using Backslash Example
let str = " Javascript \n Multiline \n String \n Example";

console.log(str);

// output: JavaScript 
//  Multiline           
//  String 
//  Example

Creating a multiline string using concatenation

For readability, it was possible to split a long string into several lines and concatenate using the (+) operator. This approach is helpful if you have multiple lines that you want to display on different lines, but your code can still get messy quickly.

JavaScript Multiline String using Concatenation Example
let str = 'JavaScript\n' +
'Multiline\n' +
'String\n' +
'Example';
 
console.log(str);

// output: JavaScript 
//  Multiline           
//  String 
//  Example

Creating a multiline string using template literals

Template literals are a recent addition to JavaScript that allows you to create multiline strings, make your code cleaner, and eliminate unnecessary special characters. For comparison, we rewrite the code above using template literal.

JavaScript Multiline String using Template Literals Example
let str = `JavaScript
Multiline
String
Example`;
 
console.log(str);

// output: JavaScript
//  Multiline
//  String
//  Example

Another advantage of template string literals is that you can use variables in a string. To do this, you use the "${variable_name}" syntax to add variables inside a string.

JavaScript Multiline String with Variable Example
let age = 31;

console.log(`Hello, my name is Leo, I'm ${age} years old.`);

// output: Hello, my name is Leo, I'm 31 years old.

See also