The question is:
What is the JavaScript method to store a multiline string into a variable like you can in PHP?
The question is:
What is the JavaScript method to store a multiline string into a variable like you can in PHP?
If by 'multiline string' you mean a string containing linebreaks, those can be written by escaping them using \n
(for newline):
var multilineString = 'Line 1\nLine 2';
alert(multilineString);
// Line 1
// Line 2
If you mean, how can a string be written across multiple lines of code, then you can continue the string by putting a \
backslash at the end of the line:
var multilineString = 'Line \
1\nLine 2';
alert(multilineString);
// Line 1
// Line 2
var es6string = `<div>
This is a string.
</div>`;
console.log(es6string);
Based on previous answers and different use cases, here is a small example:
https://gist.github.com/lavoiesl/5880516 Don't forget to use /*! to avoid the comment being removed in minification
function extractFuncCommentString(func) {
var matches = func.toString().match(/function\s*\(\)\s*\{\s*\/\*\!?\s*([\s\S]+?)\s*\*\/\s*\}/);
if (!matches) return false;
return matches[1];
}
var myString = extractFuncCommentString(function(){/*!
<p>
foo bar
</p>
*/});
Only (?) way to have multiline strings in Javascript:
var multiline_string = 'line 1\
line 2\
line 3';
This works:
var htmlString = "<div>This is a string.</div>";
This fails:
var htmlSTring = "<div>
This is a string.
</div>";
Sometimes this is desirable for readability.
Add backslashes to get it to work:
var htmlSTring = "<div>\
This is a string.\
</div>";
or this way
var htmlSTring = 'This is\n' +
'a multiline\n' +
'string';