Signup/Sign In

Multi-line Strings in JavaScript

Posted in Programming   LAST UPDATED: SEPTEMBER 4, 2021

    While writing amazing web applications in HTML, CSS and JavaScript you may come across a situation where you have to store a multi-line string in a variable in your JavaScript. In this post we will be covering three different ways of implementing multi-line string in JavaScript out of which one is based on the latest ES6 (ECMAScript 6) and the other two solutions are traditional solutions based on older JavaScript versions.

    So let's see them one by one.

    ES6 Multi-line Strings - Template literals

    In the ES6 specification, the concept of Template literals is introduced which uses backticks to define multi-line strings and for expression evaluation too in a string (more like we do in Python using format method).

    var myStr = `This is my
        multiline String
        which is amazing`;

    Some online JavaScript validators may show error in this syntax but you cna ignore them as they are the ones who are not updated yet as per the latest ES6 specifications.

    ES5 - Using backslash

    By adding a backslash at the end of every line in a multiline string works if you want to define a multiline string. This can be a bit confusing as we are adding a special symbol to escape the new line character.

    var myStr = "This is my \
        multiline String \
        which is amazing";

    By Concatenating multiple lines

    If you are old fashioned and like to write code that every one understands, you can implement a multi-line string using normal string concatenation technique where you concatenate each line of the multi-line string to the variable. Below we have a code example for it:

    var myStr = "This is my" +
       " multiline String " +
        " which is amazing";

    For concatenating strings, we use the + operator.

    Time for an Example

    Let's see the above code running in a simple code example.


    There are many different ways for defining multi-line strings and you can opt for any one. We would recommend you to go for the ES6 approach, as that is the latest one.

    You may also like:

    About the author:
    This is the official profile of the Studytonight content team.
    Tags:JavaScriptES6JavaScript Strings

    Want to learn coding and don't know where to start?

    Try out our Interactive Courses for Free 🥳 😯 🤩
    learn to code footer Ad