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.

How To Use Data Analytics To Improve Email Marketing Campaigns Top 8 Dominating Mobile App Trends in 2022 How to make a car safe for long journeys? Everything You Expect to Learn About VPN for Windows Top 7 Benefits of B2B Marketing Strategy Characteristics Held in common with All Customer-Friendly LMS Solutions