How to Create Multiline Strings in JavaScript

Answer: Use String Concatenation

String concatenation (through the + operator) can be used to create multi-line strings.

This example will demonstrate how to dynamically create HTML content in JavaScript using string concatenation, and then 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>

This is possible in an even more efficient way. Template literals can be used to quickly create multi-line strings since ES6. As shown in the following example, template literals can be used to create multi-line strings using backticks syntax ().

<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>

To learn more about the new features in JavaScript ES6 please visit our tutorial JavaScript ES6 Features.