Search

How to Create Multiline Strings in JavaScript

post-title

Use String Concatenation

You can use string concatenation (through + operator) to create a multi-line string.

The following example will show you how to compose some HTML content dynamically in JavaScript using the string concatenation and print it on a webpage.

<script>
    // Creating multi-line string
    var str = '<div class="content">' +
                  '<h1>This is a heading</h1>' +
                  '<p>This is a paragraph of text.</p>' +
              '</div>';
    
    // Printing the string
    document.write(str);
</script>

There is even better way to do this. Since ES6 you can use template literals to create multi-line strings very easily. Template literals uses backticks (`) syntax, as shown in the example below:

<script>
    // Creating multi-line string
    var str = `<div class="content">
                  <h1>This is a heading</h1>
                  <p>This is a paragraph of text.</p>
               </div>`;
    
    // Printing the string
    document.write(str);
</script>