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

Active March 09, 2022    /    Viewed 51    /    Comments 0    /    Edit


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

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>

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount