17

The question is:

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

pb2q
  • 58,613
  • 19
  • 146
  • 147
luca
  • 36,606
  • 27
  • 86
  • 125

6 Answers6

25

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
Martijn
  • 13,225
  • 3
  • 48
  • 58
15
var es6string = `<div>
    This is a string.
</div>`;

console.log(es6string);
Endless
  • 34,080
  • 13
  • 108
  • 131
9

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>
*/});
sebastien
  • 418
  • 4
  • 7
  • 2
    I've never seen this before, I don't know how practical this would be, but this is helluva creative way to handle multiline strings! +1 – Oleg Sep 13 '13 at 03:55
5

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

var multiline_string = 'line 1\
line 2\
line 3';
Björn
  • 29,019
  • 9
  • 65
  • 81
1
var myString = [
  'One line',
  'Another line'
].join('\n');
Rafael Vega
  • 4,575
  • 4
  • 32
  • 50
1

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';
Muhammad Tahir
  • 2,351
  • 29
  • 25