Create multiline string in JavaScript | Split string to Multilines

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:

  1. String concatenation and new line characters (n)
  2. Using backslash in string
  3. Using Template string literals (Recommended)

Let’s check each method with an example.

1. JavaScript Multiline string using String Concatenation and new line (n) character

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 isn" + "multi-line stringn" + "in JavaScript."

console.log(str)

Output:

This is 
multi-line string 
in JavaScript.an

Read More about String Concatenation in JavaScript.

2. Using backslash with String 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.

3. Using template literals in JavaScript to create Multi-line string

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.


Related Article:

Generate random string/characters in JavaScript

Compare Two Strings in JavaScript | String Comparison

JavaScript – How to Remove Character From A String.

Capitalize First Letter of a String – JavaScript

JavaScript – How to Remove Character From A String.

Scroll to Top