JavaScript 多行字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5391628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:02:51  来源:igfitidea点击:

JavaScript Multiline String

javascriptstringmultilineheredoc

提问by luca

The question is:

问题是:

What is the JavaScript method to store a multiline string into a variable like you can in PHP?

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

回答by Martijn

If by 'multiline string' you mean a string containing linebreaks, those can be written by escaping them using \n(for newline):

如果“多行字符串”是指包含换行符的字符串,则可以通过使用\n(换行符)将它们转义来编写:

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

回答by Endless

var es6string = `<div>
    This is a string.
</div>`;

console.log(es6string);

回答by sebastien

Based on previous answers and different use cases, here is a small example:

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

https://gist.github.com/lavoiesl/5880516Don't forget to use /*! to avoid the comment being removed in minification

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>
*/});

回答by Bj?rn

Only (?) way to have multiline strings in Javascript:

在 Javascript 中使用多行字符串的唯一 (?) 方式:

var multiline_string = 'line 1\
line 2\
line 3';

回答by Rafael Vega

var myString = [
  'One line',
  'Another line'
].join('\n');

回答by Muhammad Tahir

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';