This piece of code gives error:
var test = '1
2
3
4';
What if I want to nicely structure a code in javascript, like this:
var return = '
<div>
content
</div>
';
How do I do that?
This piece of code gives error:
var test = '1
2
3
4';
What if I want to nicely structure a code in javascript, like this:
var return = '
<div>
content
</div>
';
How do I do that?
It isn't possible to span lines like you have described.
If you use the +
operator and close your strings you can do something like this:
var retVal = '<div>' +
'content' +
'</div>';
The reason your code throws an error is because Javascript uses automatic semicolon insertion
If you want to structure a large string in multiple lines you are better off doing something like this -:
var returnValue = '<div>' +
'content' +
'</div>';
if you want to write multi line JavaScript you can use \
or if you want line breaks you can use \n
.
So something like this for multi-line:
var returnVal = '<div> \
content \
</div>';
or if you want line breaks in the output of the string:
var reutrnVal = '<div> \n content\n </div>'
or you can concatenate using '+':
var returnVal = '<div>' +
' content' +
'</div>';
JavaScript doesn't allow literal line breaks in strings. (Looks like that's wrong; see stackErr's answer, for example.) There are two semi-reasonable approaches: use the +
operator (as others have suggested), or put your lines in array and then call join('\n')
on the array:
var return = [
'<div>',
' content',
'</div>'
].join('\n');
The latter isn't really efficient, but that probably won't matter in most cases.
If you find you're doing this a lot (assembling many little HTML snippets programmatically), it would be worth looking into a template library such as Mustache.
If you end a line with a \
, then your string can continue on the next line.
var return = '\
<div>\
content\
</div>\
';
There's a nice trick for creating multi-line strings in JavaScript which don't involve escaping the line feeds for every line, described at http://tomasz.janczuk.org/2013/05/multi-line-strings-in-javascript-and.html. Basically, you'd define a function with only a comment containing the multi-line string you want, call toString
on that function and strip out the comment, like in this example below:
var html = (function () {/*
<!DOCTYPE html>
<html>
<body>
<h1>Hello, world!</h1>
</body>
</html>
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];