18

The question is:

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

pb2q
59.9k19 gold badges150 silver badges152 bronze badges
asked Mar 22, 2011 at 13:00
2
  • 1
    What do you mean by "grab"? From where? Commented Mar 22, 2011 at 13:01
  • check my answer on stackoverflow.com/a/19970452/209797 Commented Nov 14, 2013 at 5:53

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
answered Mar 22, 2011 at 13:24
Sign up to request clarification or add additional context in comments.

Comments

15
var es6string = `<div>
 This is a string.
</div>`;
console.log(es6string);
answered Sep 18, 2015 at 18:14

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>
*/});
answered Jun 27, 2013 at 21:33

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';
answered Mar 22, 2011 at 13:02

Comments

1
var myString = [
 'One line',
 'Another line'
].join('\n');
answered Jul 28, 2015 at 19:57

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';
answered Aug 20, 2015 at 13:25

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.