Creating Multiline Strings in Javascript

Creating Multiline Strings in Javascript

I have the following code in Ruby. I want to convert this code into JavaScript. What is the equivalent code in JS?

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

43 Answers

Update:

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 here-document syntax. You can escape the literal newline, however, which comes close:

"foo \
bar"
24

ES6 Update:

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'
Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.