Open In App

How to write multi-line strings in template literals ?

Template literals are introduced in ES6 and by this, we use strings in a modern way. Normally for defining string, we use double/single quotes ( ” ” or ‘ ‘ ) in JavaScript. But in template literals, we use backtick ( ` ` ).

Let us see how to write multiline strings in template literals.



Example 1: We write multiline string by template literals.




const multilineString = `How
are you
doing
I am fine`;
 
console.log(multilineString);

Output:



How      
are you  
doing    
I am fine

Example 2: If you use double/single quote to write multiline string then we use the newline character (\n).  Use an extra backslash ( \ ) after every newline character (\n), this backslash tells the JavaScript engine that the string is not over yet.




var multilineString =
"How \n\
are you \n\
doing \n\
I am fine";
 
console.log(multilineString);

Output:

How 
are you
doing
I am fine
Article Tags :