How to create a string variable on multiple lines in javascript ?

Published: March 09, 2022

Updated: December 09, 2022

Tags: Javascript;

DMCA.com Protection Status

Examples of how to create a string variable on multiple lines in javascript

Table of contents

Example 1

To create a string variable on multiple lines in javascript, a solution is to use a template literal which is delimited by backticks ``:

var s = `an example of a very very
                    very very very very very very
                    very veryvery very long string`

console.log( s );

Example 2

Another example with aninnerHTML :

    <!DOCTYPE html>
    <html lang="en" dir="ltr">
        <head>
            <meta charset="utf-8">
            <title></title>
        </head>
        <body>

            <div id="intro">
                    <h1>Learning Javascript</h1>
                    <p>First paragraph</p>
            </div>

            <script>

                document.querySelector("#intro").innerHTML +=
                    `<p>Second paragraph</p>
                     <p>Third paragraph</p>
                     <p>Fourth paragraph</p>`;

            </script>

        </body>
    </html>