How to Create Multiline Strings in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: 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.
Example
Try this code »<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:
Example
Try this code »<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>
Check out the tutorial on JavaScript ES6 features to learn about new features introduced in ES6.
Related FAQ
Here are some more FAQ related to this topic: