There are times when you want to assign a rather long html description to a variable, such as when using jQuery’s append
In this article, I will explain how to assign a string containing a newline to a variable in JavaScript.
Using “`” backquotes
This is a simple way to enclose a string containing a newline with “`” backquotes.
Sample
var userInfo = ` <div class="user"> <div class="close">✕</div> <div class="message">Sample JavaScript</div> <a href="#" class="btn-basic">OK</a> </div> `;
Of course, it is also possible to combine strings and variables within a variable.
var btnClass = "btn-basic"; var userInfo = ` <div class="user"> <div class="close">✕</div> <div class="message">Sample JavaScript</div> <a href="#" class="` + btnClass + `">OK</a> </div> `;
The “`” backquote can usually be entered with “SHIFT + @”. Just enclose it in back-quotes, so it’s easy!
Write “\” in the newline section
Another way is to write a “\” backslash in the newline section.
var userInfo = '\ <div class="user">\ <div class="close">✕</div>\ <div class="message">Sample JavaScript</div>\ <a href="#" class="btn-basic">OK</a>\ </div>\ ';
You just need to write “\” where the line break occurs as shown above, but it’s more work than “`” backquoting.
It makes the description easier to understand when you have to append long html with jQuery.