问题是:
像在 PHP 中那样将多行字符串存储到变量中的 JavaScript 方法是什么?
\n
如果“多行字符串”是指包含换行符的字符串,则可以通过使用(换行符)转义它们来编写:
var multilineString = 'Line 1\nLine 2';
alert(multilineString);
// Line 1
// Line 2
如果您的意思是,如何跨多行代码编写字符串,那么您可以通过\
在行尾添加反斜杠来继续字符串:
var multilineString = 'Line \
1\nLine 2';
alert(multilineString);
// Line 1
// Line 2
var es6string = `<div>
This is a string.
</div>`;
console.log(es6string);
根据之前的答案和不同的用例,这里有一个小例子:
https://gist.github.com/lavoiesl/5880516 不要忘记使用 /*!避免在缩小中删除评论
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>
*/});
只有(?)在Javascript中使用多行字符串的方法:
var multiline_string = 'line 1\
line 2\
line 3';
var myString = [
'One line',
'Another line'
].join('\n');
这有效:
var htmlString = "<div>This is a string.</div>";
这失败了:
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';