The best way to use multiple-line string in javascript

Javascript does not allow multi -line string constant.

var html='
<div>
    <span> hello world</span>
</div>
';
alert(html);

This will produce an error:”unterminated string literal“. To write multi-line string, you have to append a back slash to each line as follow:

var html='\
<div>\
    <span> hello world</span>\
</div>\
';
alert(html);

There should not be spaces after the back slashes[reference]. Note that the string does not include the new line(10) and carriage return(13) characters even they are included in your script(but other invisible characters such as TAB(9) are preserved). In other words, the back slashes and the invisible new line and carriage return characters you write in your script are only used by the parser of javascript and stripped by the parser in the end.  There are other ways to write the multi-line string constant. You can separate the string into multiple single-line strings and concatenate them using “+”, or push them into an array then use the join function of the array to get the result string.    Either way, however, is ugly and makes the string look not natural. The best way to write a multi-line string in script is as follows:

<div id="mymultilinestring" style="display:none">
<div>
    <span> hello world</span>
</div>
</div>
<script>
var html=document.getElementById("mymultilinestring").innerHTML;
alert(html);
</script>

i.e, surround the multi-line string with an invisible div element, then get the string thru the innerHTML property of the div element. This way, you do not need to add back slash at the end of each line, but also have the ability of preserving the new line characters within the string.

reference:https://stackoverflow.com/questions/5296402/unterminated-string-literal

Comments are closed, but trackbacks and pingbacks are open.