How to Create Multiline Strings in JavaScript

  995 views   1 year ago Javascript

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>

 

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]

Related Articles