Creating Multi-line Strings in Javascript with Template Literals

Published on January 29, 2019

Using the + concatenation operator is the most commonly used to create multi-line strings. But ES6 has brought forward a better method to do so.

Using Template Literals to Create Multi-line Strings

Template literals are specified using the back-tick character ` instead of the normal ' or " characters.

var str = `This is a sentence`;

With template literals you can extend a line to multiple lines.

var str = `This is the first line
This is the second line
And this is the third`;

Substituting Variables in the Template Literal String

Placeholders for variables and expressions can be created using the ${variable} syntax.

var a = 1;
var b = 2;

var str = `${a} + ${b} equals ${a+b}`;

// outputs "1 + 2 equals 3"

You can even nest another template literal inside the ${ } placeholder.

var a = 2;
var b = 1;

var str = `The value is set to ${ a == 1 ? 'TREE' : `ANIMAL-${ b == 1 ? 'ONE' : 'TWO' }` }`;

// outputs "The value is set to ANIMAL-ONE"
In this Tutorial