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
- The + operator
- The \ operator
Now, let’s explore the above methods one by one to achieve this task.
Multiline strings using template literals
Template literals are literals separated by backticks. It interpolates strings with the embedded expressions and also allows us to create multiline strings.
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
This is an addition or concatenation operator that concatenates two operands of JavaScript. The + operator also allows us to add strings.
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
This is a backslash operator and escape character of JavaScript.
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