snippetjavascriptCritical
How can I assign a multiline string literal to a variable?
Viewed 0 times
literalmultilinehowvariablecanstringassign
Problem
How do I convert this Ruby code with a multiline string into JavaScript?
`text =
`text =
Solution
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:
(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:
A template literal is delimited by backticks:
var html = `
Some HTML here
`;(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"Code Snippets
var html = `
<div>
<span>Some HTML here</span>
</div>
`;"foo \
bar"Context
Stack Overflow Q#805107, score: 4556
Revisions (0)
No revisions yet.