Creating multiline strings in JavaScript

Asked : Nov 17

Viewed : 67 times

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
javascript string multiline heredoc 

Nov 17

4 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"

answered Jan 17


I'm surprised I didn't see this because it works everywhere I've tested it and is very useful for e.g. templates:

<script type="bogus" id="multi">
    My
    multiline
    string
</script>
<script>
    alert($('#multi').html());
</script>

Does anybody know of an environment where there is HTML but it doesn't work?

answered Jan 17


JavaScript never had a truly good way to handle multiline strings, until 2015 when ES6 was introduced, along with template literals.

Template literals are strings delimited by backticks, instead of the normal single/double quote delimiter.

They have a unique feature: they allow multiline strings:

const multilineString = `A string
on multiple lines`

const anotherMultilineString = `Hey
this is cool
a multiline
st
r
i
n
g
!
`

answered Jan 17


Create Multiline Strings Using +

// program to create a multiline strings

// using the + operator
const message = 'This is a long message\n' + 
    'that spans across multiple lines\n' + 
    'in the code.'

console.log(message);

Output

This is a long message
that spans across multiple lines
in the code.
In the above example, a multiline string is created using the + operator and \n.
The escape character \n is used to break the line.

answered Jan 17


Login and Submit Your Answer
Browse other questions tagged  javascript  string  multiline  heredoc or ask your own question.