How to Create a Multiline String in JavaScript?

Estimated read time 1 min read

In JavaScript, you can create a multiline string by using template literals, which are string literals that allow for embedded expressions and multi-line strings. Template literals are defined using backticks (`) instead of single or double quotes (' or ").

Here’s an example of how you could create a multiline string using template literals:

let multilineString = `This is a
multiline string.`;

In this example, the multilineString variable is assigned a string literal that contains line breaks, which are preserved in the string. When logged to the console, the string will be displayed exactly as it is defined, with line breaks included.

Template literals can also include expressions that are evaluated and included in the resulting string. Here’s an example:

let name = 'John';
let age = 30;
let multilineString = `My name is ${name} and I am ${age} years old.`;

In this example, the ${name} and ${age} expressions are evaluated and replaced with the corresponding values before the string is created. The resulting string will be My name is John and I am 30 years old..

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply