Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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
share|improve this question
    
See stackoverflow.com/a/6247331/632951 – Pacerier Apr 30 '14 at 19:25
    
Check this out on different ways to achieve the same. I have added performance of each method too stackoverflow.com/a/23867090/848841 – vignesh Jul 17 '14 at 5:42
    
Can you please update the answer? It's 2015 now and JavaScript has multiline strings – mikemaccana Oct 11 '15 at 21:44

32 Answers 32

I think I discovered another way to do it inline without any invasive syntax on every line. Use Javascript's ability to convert a function to string and create a multiline comment with the /**/ syntax then remove the "function() {/*\n" and "\n*/}".

var multiline = function(string) { return string.toString().replace(/(^[^\n]*\n)|(\n\*\/\})/g, ""); };

console.log(multiline(function() {/*
Hello world!
I'm a multiline string!

Tada!
*/}));

The only pitfall I can see in this is the syntax highlighting.

EDIT: Had I scrolled down a little more, I would have seen this answer doing exactly the same thing: http://stackoverflow.com/a/5571069/916553

share|improve this answer

It's not extremely elegant but it's clean enough for me:

var myString = "First line" + "\n";
var myString = myString + "Second line" + "\n";
var myString = myString + "Third line" + "\n";
share|improve this answer
12  
You should use var myString += "Second line \n"; instead. MUCH cleaner. – Colin Feb 27 '13 at 4:45
8  
Actually, you should use myString += "Second line \n"; The var shouldn't be repeated. – Michael Mior Jul 11 '13 at 14:04
1  
use + only for concatenate strings. Not need declare all buffer for each line. Its horrorific. – e-info128 Aug 2 '13 at 15:43
1  
Should I correct my answer or should I leave it there as a good example of how NOT to do things? If it's best for the people who learn JavaScript, I don't mind leaving it there as it is now. A few negative points can't hurt that much. – Bear Bear Nov 26 '14 at 1:04
    
I would suggest removing it... – Druzion Jan 28 at 14:44

protected by Travis J Dec 12 '13 at 3:03

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.