18

The question is:

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

2

6 Answers 6

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
Sign up to request clarification or add additional context in comments.

Comments

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

console.log(es6string);

3 Comments

Note: This only works with ES6 and, at the time of this writing, is not well supported in IE11 or Safari.
This is becoming the correct answer.
Ugh why does JS need to reinvent the wheel. This should be a subprocess.
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>
*/});

1 Comment

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
5

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

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

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.