How can I assign a multiline string literal to a variable?

3.5k2009 年提問 · Newy ·javascriptstringmultilineheredoc 主題:字串與正規 → 在 Stack Overflow 看原文 ↗

How do I convert this Ruby code with a multiline string into JavaScript?

text = <<"HERE"
This
Is
A
Multiline
String
HERE

重點答案

4.6k採納 by Anonymous 原文 ↗

ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.

A template literal is delimited by backticks:

var html = `
  <div>
    <span>Some HTML here</span>
  </div>
`;

(Note: I'm not advocating to use HTML in strings)

Browser support is OK, but you can use transpilers to be more compatible.


Original ES5 answer:

JavaScript doesn't have a heredoc syntax. You can escape the literal newline, however, which comes close:

"foo \
bar"

ES6

As the first answer mentions, with ES6/Babel, you can now create multi-line strings simply by using backticks:

const htmlString = `Say hello to 
multi-line
strings!`;

Interpolating variables is a popular new feature that comes with back-tick delimited strings:

const htmlString = `${user.name} liked your post about strings`;

This just transpiles down to concatenation:

user.name + ' liked your post about strings'

ES5

Google's JavaScript style guide recommends to use string concatenation instead of escaping newlines:

Do not do this:

var myString = 'A rather long string of English text, an error message \
                actually that just keeps going and going -- an error \
                message to make the Energizer bunny blush (right through \
                those Schwarzenegger shades)! Where was I? Oh yes, \
                you\'ve got an error and all the extraneous whitespace is \
                just gravy.  Have a nice day.';

The whitespace at the beginning of each line can't be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript.

Use string concatenation instead:

var myString = 'A rather long string of English text, an error message ' +
               'actually that just keeps going and going -- an error ' +
               'message to make the Energizer bunny blush (right through ' +
               'those Schwarzenegger shades)! Where was I? Oh yes, ' +
               'you\'ve got an error and all the extraneous whitespace is ' +
               'just gravy.  Have a nice day.';

The pattern text = <<"HERE" This Is A Multiline String HERE is not available in JavaScript (I remember using it much in my good old Perl days).

To keep oversight with complex or long multiline strings I sometimes use an array pattern:

var myString =
   ['<div id="someId">',
    'some content<br />',
    '<a href="#someRef">someRefTxt</a>',
    '</div>'
   ].join('\n');

Or the pattern Anonymous already showed (escape newline), which can be an ugly block in your code:

    var myString =
       '<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';

Here's another weird, but working, 'trick'1:

var myString = (function () {/*
   <div id="someId">
     some content<br />
     <a href="#someRef">someRefTxt</a>
    </div>
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

External edit: jsfiddle

ES20xx supports spanning strings over multiple lines using template strings:

let str = `This is a text
    with multiple lines.
    Escapes are interpreted,
    \n is a newline.`;
let str = String.raw`This is a text
    with multiple lines.
    Escapes are not interpreted,
    \n is not a newline.`;

1 Note: this will be lost after minifying/obfuscating your code