Creating multiline strings in JavaScript

There are many ways where we could easily create multiline strings using JavaScript. Some of the best methods are listed in the below examples.

Creating multiline strings in JavaScript can be achieved by concatenating the strings together or by using Backlash character or by using a special delimiter called backticks.

String concatenation is the easiest part, however, it’s not recommended approach since there will be an impact in the Speed and the performance factor. The best approach is to use a delimiter ‘\’ to create multiline strings.

Creating multiline strings in JavaScript by concatenation

var multiLineString = "This is an example of concatenating" +
"two lines together";

JavaScript Multiline string using delimiter

var multiLineString = "This is an example of concatenating \
two lines together \
appending one more line here...";

The above example using backslash as a delimiter is the best approach to Create multiline JavaScript Strings. Note in the above example the backslash tells the javascript engine to continue to next line rather than inserting the automatic semicolon.

ECMAScript6(ES6) introduces a new type of literal called as template literals. One of the features is multiline strings using the backticks.

JavaScript multiline string using template literal backticks (`)

var multiLineString = `his is an example of concatenating
two lines together
appending one more line here...`;

 

Leave a Reply

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

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like