Home » Programming » Javascript » Javascript Multiline String

Creating Multiline Strings in JavaScript [With Examples]

There are several ways to create text that spans multiple lines in JavaScript – so here they are!

Method 1: Backticks

This is the best method, so it goes first. It is only compatible with ECMAScript 6 and onwards, so it is only for use in modern browsers (really, if you’re using any browser that isn’t Internet Explorer, you should be fine, but you should always test your code on the browsers you want to target).

var multiText = `
    This is
    multiline
    text!`;

console.log(multiText) // Will output text, on multiple lines

Simply wrapping the multi-line text (including the new lines) in backticks instead of quotes will create proper multi-line text.

This is called a Template Literal, a type of string variable that allows for embedded expressions and new lines.

Method 2: Escape the Newline Character

You can add a backslash (\) at the end of each line in a single or double-quoted string to escape the invisible new-line character which follows it so that it is included in the string rather than parsed:

var multiText = "\
    This is \
    multiline \
    text!";

console.log(multiText) // Will output text, on multiple lines

This method should work on older browsers but is generally not recommended.

Remember that you may need to remove code indentation if you’re getting odd gaps in your text.

Conclusion

While you’re manipulating JavaScript Strings, why not try:

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment