JavaScript multiline string Best Way and Examples

You can have multiline strings in pure JavaScript. In ES6 Update, you can create multi-line strings simply by using backticks.

The multi-line strings were not supported by JavaScript 2015.

ECMAScript 6 (ES6) introduces a new type of literal, namely template literals.

Template literals are strings delimited by backticks, instead of the normal single/double quote delimiter.

JavaScript multiple line string Example

It have a unique feature to allow multiline strings.

Output:

JavaScript multiline string

Other ways to JavaScript multiline string

There are various ways to handle multi-line strings if older browser support is essential.

Using template literals with different Tags

The strings are delimited using backticks, unlike normal single/double quotes delimiter.

Output:

JavaScript multiline string example

Multiline string without newlines

If you introduce a line continuation (\) at the point of the new line in the literal, it won’t create a new line on output:

How to JavaScript multiline string with variables

You can take advantage of Template Literals and use this syntax:

Template literals are enclosed by the back-tick ( ) (grave accent) instead of double or single quotes.

This feature has been introduced in ES2015 (ES6).

Example

Q: Can we do javascript multiline string with newlines (\n)?

Answer: Don’t use “\n”. Just enter a back-slash and keep on truckin’! Works like a charm. Example:-

How to concatenate multiline string in javascript?

Answer:

  • \ – regular escape, if you need the quote in your string just type \’
  • \n – newline
  • \t – tab

Use this method to concatenate multiline string in js.

How to JavaScript split multi-line string to array?

Answer: Use split() Method to multiline string to array.

Output:

[“abc”, “def”]

Do comment if you have any questions, doubts and suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.