Create multiline strings in JavaScript

In this tutorial, you will see how to create multiline strings in JavaScript. There are three ways presented below to create strings that span multiple lines.

  • Template literals: Template literals are literals separated by backticks. It interpolates strings with the embedded expressions and also allows us to create multiline strings.
  • The + operator: This is an addition or concatenation operator that concatenates two operands of JavaScript. The + operator also allows us to add strings.
  • The \ operator: This is a backslash operator and escape character of JavaScript.

 

Multiline strings using template literals

const message = `Hey there
welcome to
Codespeedy.`
console.log(message);

In the above program, I have used template literal `` to create multiline strings.

Output:

Hey there 
welcome to 
Codespeedy.

 

Multiline string using the + operator

const message = 'Hey there \n' +
'welcome to \n' +
'Codespeedy.'
console.log(message);

In the above program, the + operator to create multiline strings and the escape character \n to break the line and bring up sentences on a new line.

Output:

Hey there 
welcome to 
Codespeedy.

Using the \ operator

const message = 'Hey there \n \
welcome to \n \
Codespeedy.'
console.log(message);

In the above program, I have created a multiline string with single quotes.

The escape character \n to break the line and bring up sentences on a new line then the \ operator to create multiline strings.

Output:

Hey there
welcome to
Codespeedy.

Leave a Reply

Your email address will not be published. Required fields are marked *