JavaScript Multiline String [duplicate]

余生长醉 提交于 2019-12-23 07:00:08

问题


The question is:

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


回答1:


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



回答2:


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

console.log(es6string);



回答3:


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



回答4:


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

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



回答5:


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



回答6:


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


来源:https://stackoverflow.com/questions/5391628/javascript-multiline-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!