In this post, we will see how to create a multiline string in JavaScript.
To create a multiline string in Javascript we can use these three methods:
\n
)Let's check each method with an example.
To create a multiline we can use the new line character ( \n
) in our string. It is used to span our string across multiple lines.
const str = "This is \nmulti-line string \nin JavaScript."
console.log(str)
Output:
This is
multi-line string
in JavaScript.
Now, if we have multiple strings that you want to span across multiple lines then we can use the new line character \n
for line break alone with the concatenation operator (+
).
const str = "This is\n" + "multi-line string\n" + "in JavaScript."
console.log(str)
Output:
This is
multi-line string
in JavaScript.an
Read More about String Concatenation in JavaScript.
Another method to create a multiline string in JavaScript is to use the backslash (\
) in the string.
const str = "This is \n \
multi-line \n \
String."
console.log(str)
The backslash ( \
) placed at the end of the \n
tells the JavaScript engine that the string will continue to the subsequent line. It avoids the automatic insertion of the semicolon (;
) by JavaScript.
Output:
This is
multi-line
String
The above two methods were used before the introduction of ES6. In ES5, we had to manually insert new line use (
\n
).
However, with the introduction of ES6, now we can use the string literals to create multi-line easily without using newline characters in JavaScript.
Template literals are defined as literals that are delimited with backticks characters (`
). It is used for multi-line strings or for string interpolation with expressions.
We can create a new line using the Enter key inside the template literal.
const str = `This is
a multi-line string
using template literals.`
console.log(str)
Output:
This is
a multi-line string
using template literals.
Here, we just have to write our string inside the backticks (``
) and hit enter for a new line.
Read more about Template String Literals and String Interpolations.