The question is:
What is the JavaScript method to store a multiline string into a variable like you can in PHP?
-
1What do you mean by "grab"? From where?Unicron– Unicron2011年03月22日 13:01:13 +00:00Commented Mar 22, 2011 at 13:01
-
check my answer on stackoverflow.com/a/19970452/209797AgelessEssence– AgelessEssence2013年11月14日 05:53:09 +00:00Commented Nov 14, 2013 at 5:53
6 Answers 6
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
Comments
var es6string = `<div>
This is a string.
</div>`;
console.log(es6string);
3 Comments
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>
*/});
1 Comment
Only (?) way to have multiline strings in Javascript:
var multiline_string = 'line 1\
line 2\
line 3';
Comments
var myString = [
'One line',
'Another line'
].join('\n');
Comments
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';
Comments
Explore related questions
See similar questions with these tags.