To create multiline strings in JavaScript, you can use the backticks (``
) in JavaScript.
Consider this HTML string,
const htmlStr = "<div><h1>Heading</h1><p>A paragrapgh</p></div>";
This string looks super ugly and very hard to read 😱.
Even if we try to make a new line in the above string by pushing the contents to a new line, JavaScript will throw an error because here we are using double quotes to wrap the string.
// This is an error in JavaScript
// You can't do this ❌
const htmlStr = "<div>
<h1>Heading</h1>
<p>A paragrapgh</p>
</div>";
console.log(htmlStr); // Error: Invalid or unexpected token
This is where backticks come into play.
All we have to do is switch the double quotes (""
) with backticks (``
) like this,
// Switch double quotes with backticks
// Now you can create strings that strechtes to
// Multi lines ✅
const htmlStr = `
<div>
<h1>Heading</h1>
<p>A paragrapgh</p>
</div>
`;
console.log(htmlStr);
/*
<div>
<h1>Heading</h1>
<p>A paragrapgh</p>
</div>
*/
Now we have a clean, readable string that stretches to multiple lines.
See this example live in JSBin.