14

问题是:

像在 PHP 中那样将多行字符串存储到变量中的 JavaScript 方法是什么?

4

6 回答 6

24

\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
于 2011-03-22T13:24:53.170 回答
13
var es6string = `<div>
    This is a string.
</div>`;

console.log(es6string);
于 2015-09-18T18:14:58.630 回答
8

根据之前的答案和不同的用例,这里有一个小例子:

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>
*/});
于 2013-06-27T21:33:51.377 回答
4

只有(?)在Javascript中使用多行字符串的方法:

var multiline_string = 'line 1\
line 2\
line 3';
于 2011-03-22T13:02:19.033 回答
1
var myString = [
  'One line',
  'Another line'
].join('\n');
于 2015-07-28T19:57:45.270 回答
1

这有效:

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';
于 2015-08-20T13:25:57.490 回答