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

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

Comments are closed, but trackbacks and pingbacks are open.