I have the following code in Ruby. I want to convert this code into JavaScript. what's the equivalent code in JS?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
I have the following code in Ruby. I want to convert this code into JavaScript. what's the equivalent code in JS?
text = <<"HERE"
This
Is
A
Multiline
String
HERE
You can have multiline strings in pure JavaScript.
This method is based on the serialization of functions, which is defined to be implementation-dependent. It does work in the most browsers (see below), but there's no guarantee that it will still work in the future, so do not rely on it.
Using the following function:
You can have here-documents like this:
The method has successfully been tested in the following browsers (not mentioned = not tested):
Be careful with your minifier, though. It tends to remove comments. For the YUI compressor, a comment starting with
/*!
(like the one I used) will be preserved.I think a real solution would be to use CoffeeScript.
If you're willing to use the escaped newlines, they can be used nicely. It looks like a document with a page border.
Easiest way to make multiline strings in Javascrips is with the use of backticks ( `` ). This allows you to create multiline strings in which you can insert variables with
${variableName}
.Example:
compatibility :
ES6
//es2015
Check exact compatibility in Mozilla docs here
I think this workaround should work in IE, Chrome, Firefox, Safari, Opera -
Using jQuery :
Using Pure Javascript :
Cheers!!
If you happen to be running in Node only, you could use the fs module to read in the multi-line string from a file:
This works in IE, Safari, Chrome and Firefox: