How to create a multi-line string in JavaScript

To create a multi-line string in JavaScript, you can use template literals. Template literals were introduced in ES6 and provide a modern way to work with strings.

Unlike regular strings that use a single/double quote as a delimiter, template-literal strings are delimited by the backtick (`) character.

Template literals have many features like variable interpolation, tagged templates, to name a few, but most importantly, they can be multi-line.

const multiStr = `
    Hey there!
    How are you?
    Do you 
    have 
    time
    for a
    quick 
    call?
`;

Before ES6, you have to manually append a newline character (\n) to create a multi-line string:

var multiStr = 'This is \n\
an example of \n\
multi-line string';

Note that the backslash (\) placed after the newline character (\n) at the end of each line tells the JavaScript engine that the string will continue to the subsequent line. This is necessary to avoid automatic semicolon insertion by the JavaScript engine.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.