Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
47  
I find most of these answers to be terrifying... –  Steven Hunt Nov 8 '12 at 14:11

23 Answers

up vote 357 down vote accepted

Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:

"foo \
bar"
share|improve this answer
81  
Be warned: some browsers will insert newlines at the continuance, some will not. –  staticsan Apr 30 '09 at 2:22
12  
Visual Studio 2010 seems to be confused by this syntax as well. –  jcollum Apr 17 '11 at 21:58
10  
dresende: It's two lines of code. It's a single expression. –  Anonymous Mar 29 '12 at 20:02
38  
Unfortunately this is not allowed by the standard, although implementations do support it. (Very last paragraph of ECMA-262 3rd Edition section 7.8.4). –  Nate Apr 10 '12 at 19:19
24  
@Nate It is specified in ECMA-262 5th Edition section 7.8.4 and called LineContinuation : "A line terminator character cannot appear in a string literal, except as part of a LineContinuation to produce the empty character sequence. The correct way to cause a line terminator character to be part of the String value of a string literal is to use an escape sequence such as \n or \u000A." –  some Sep 25 '12 at 2:28
show 7 more comments

the pattern text = <<"HERE" This Is A Multiline String HERE is not available in js (I remember using it much in my good old Perl days).

To keep oversight with complex or long multiline strings I sometimes use an array pattern:

var myString = 
   ['<div id="someId">',
    'some content<br />',
    '<a href="#someRef">someRefTxt</a>',
    '</div>'
   ].join('\n');

or the pattern anonymous already showed (escape newline), which can be an ugly block in your code:

    var myString = 
       '<div id="someId"> \
some content<br /> \
<a href="#someRef">someRefTxt</a> \
</div>';
share|improve this answer
9  
Please don't use the array pattern. It will be slower than plain-old string concatenation in most cases. –  BMiner Jul 17 '11 at 12:39
68  
Really? jsperf.com/join-concat/24 –  KooiInc Jul 17 '11 at 13:21
38  
The array pattern is more readable and the performance loss for an application is often negligible. As that perf test shows, even IE7 can do tens of thousands of operations per second. –  Ben Atkin Aug 20 '11 at 8:16
8  
+1 for an elegant alternative that not only works the same way in all browsers, but is also future-proof. –  Pavel May 21 '12 at 6:06
4  
@KooiInc Your tests start with the array already created, that skews the results. If you add the initialization of the array, straight concatenation is faster jsperf.com/string-concat-without-sringbuilder/7 See stackoverflow.com/questions/51185/… As a trick for newlines, it may be OK, but it's definitely doing more work than it should –  Juan Mendes Aug 4 at 8:02
show 9 more comments

Google's javascript style guide recommends to use string concatenation instead of escaping newlines because the latter isn't a part of ECMAscript:

http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Multiline_string_literals#Multiline_string_literals

Update

In EcmaScript 6, you'll be able to use backticks for Template Strings, known in the spec as a NoSubstitutionTemplate:

var htmlString = `Say hello to 
multi-line
strings!`;

I think you can try this and other features by first downloading canary chrome and then turning on Enable Experimental JavaScript

share|improve this answer
51  
+1 for actually making reference to the standard –  luke Feb 9 '12 at 14:19
13  
+1 for future proofing this question! –  Gerald Kaszuba May 17 '12 at 5:48
 
this doesn't work for me in canary chrome for windows even after enabling Experimental JavaScript –  Inuart Nov 20 '12 at 1:09
 
I don't understand Google's recommendation. All browsers except extremely old ones support the backslash followed by newline approach, and will continue to do so in the future for backward compatibility. The only time you'd need to avoid it is if you needed to be sure that one and only one newline (or no newline) was added at the end of each line (see also my comment on the accepted answer). –  Matt Browne Feb 26 at 18:40
 
Those who want to try these stuffs, be sure to check [Chrome Canary][1] [1]: google.com/intl/en/chrome/browser/canary.html –  Sazid Oct 31 at 5:31

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:

function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*!?/, '').
      replace(/\*\/[^\/]+$/, '');
}

You can have here-documents like this:

var tennysonQuote = hereDoc(function() {/*!
  Theirs not to make reply,
  Theirs not to reason why,
  Theirs but to do and die
*/});

The method has successfully been tested in the following browsers (not mentioned = not tested):

  • IE 4 - 10
  • Opera 9.50 - 12 (not in 9-)
  • Safari 4 - 6 (not in 3-)
  • Chrome 1 - 27
  • Firefox 17 - 21 (not in 16-)
  • Rekonq 0.7.0 - 0.8.0
  • Not supported in Konqueror 4.7.4

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.

share|improve this answer
9  
+1+1 Clever! (works in Node.JS) –  George Bailey Jun 4 '11 at 21:57
109  
What!? creating and decompiling a Function to hack a multiline comment into being a multiline string? Now that's ugly. –  fforw Jun 17 '11 at 15:49
29  
You, sir, are extremely clever. +1 for that, although I'll probably never use this particular solution. –  Roy Tinker Jun 17 '11 at 20:13
10  
And that makes you even more clever. –  Jordão Jun 17 '11 at 20:17
5  
+1 "So please NEVER use it" –  tomwrong Aug 24 '11 at 9:22
show 17 more comments

You can do this...

var string = 'This is ' +
'multiline' + 
'string';
share|improve this answer
9  
You learn something new everyday –  Itay Moav -Malimovka Apr 30 '09 at 2:28
1  
Forgive my ignorance, but with's with the <r></r> –  Jordan S. Jones Apr 30 '09 at 2:30
1  
<r> is just an xml fragment, and the CDATA is the node. –  alex Apr 30 '09 at 2:36
3  
As far as I know the second example will only work in Firefox –  KooiInc Apr 30 '09 at 7:44
12  
The second example is using E4X, which is why it only works in Firefox. It does work fine in either HTML or XHTML though. The <r></r> part could be anything (even empty: <></>). –  Matthew Crumley Apr 30 '09 at 14:30
show 9 more comments

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?

share|improve this answer
13  
Anywhere you don't want to put your strings into seperate and distant script elements. –  Lodewijk Jan 9 '12 at 1:12
6  
A valid objection! It isn't perfect. But for templates, that separation is not only ok, but perhaps even encouraged. –  Peter V. Mørch Feb 3 '12 at 9:03
1  
I prefer splitting everything over 80/120 characters into multiline, I'm afraid that's more than just templates. I now prefer 'line1 ' + 'line2' syntax. It's also the fastest (although this might rival it for really large texts). It's a nice trick though. –  Lodewijk Feb 3 '12 at 22:51
9  
actually, this is HTML not Javascript :-/ –  CpILL May 22 '12 at 8:54
1  
however, the task of obtaining a multiline string in javascript can be done this way –  Davi Fiamenghi Jul 30 at 21:41
show 1 more comment

I came up with this very jimmy rigged method of a multi lined string. Since converting a function into a string also returns any comments inside the function you can use the comments as your string using a multilined comment /**/. You just have to trim off the ends and you have your string.

var myString = function(){/*
    This is some
    awesome multi-lined
    string using a comment 
    inside a function 
    returned as a string.
    Enjoy the jimmy rigged code.
*/}.toString().slice(14,-3)

alert(myString)
share|improve this answer
4  
Wow. That's, uh, creative. :) –  Nick Cox Mar 28 at 9:51
9  
This is absolutely terrifying. I love it (although you may need to do a regex match because I'm not sure how precise the whitespace for toString() is. –  Kevin Cox Apr 7 at 21:53
4  
 
This solution does not seem to work in firefox, maybe it's a security feature for the browser? EDIT: Nevermind, it only does not work for Firefox Version 16. –  Yongke Bill Yu Jun 6 at 19:18
2  
Also beware of minifiers that strip comments... :D –  jondavidjohn Oct 22 at 19:07

I solved this by outputting a div, making it hidden, and calling the div id by jQuery when i needed it.

e.g.

<div id="UniqueID" style="display:none;">
     Strings
     On
     Multiple
     Lines
     Here
</div>

Then when i need to get the string, i just use the following jQuery:

$('#UniqueID').html();

Which returns my text on multiple lines. If i call

alert($('#UniqueID').html();

I get:

enter image description here

share|improve this answer
1  
Thanks for this! It's the only answer I've found that solves my problem, which involves unknown strings that may contain any combination of single and double quotes being directly inserted into the code with no opportunity for pre-encoding. (it's coming from a templating language that creates the JS -- still from a trusted source and not a form submission, so it's not TOTALLY demented). –  octern Jun 23 at 17:19
 
This was the only method that actually worked for me to create a multi-line javascript string variable from a Java String. –  beginner_ Aug 6 at 12:06
 
this gets the work done for me, although it doesnot solve multiline string values assignment to javascript variables –  Venkat Sep 23 at 16:24

I like this syntax and indendation:

string = 'my long string...\n'
       + 'continue here\n'
       + 'and here.';

(but actually can't be considered as multiline string)

share|improve this answer
1  
I use this, except I put the '+' at the end of the preceding line, to make it clear the statement is continued on the next line. Your way does line up the indents more evenly though. –  Sean Oct 4 '12 at 8:54
 
@Sean i use this too, and i still prefer put the '+' at the beginning of each new line added, and the final ';' on a new line, cuz i found it more 'correct'. –  iim.hlk yesterday

Using script tags:

  • add a <script>...</script> block containing your multiline text into head tag;
  • get your multiline text as is... (watch out for text encoding: UTF-8, ASCII)

    <script>
    
        // pure javascript
        var text = document.getElementById("mySoapMessage").innerHTML ;
    
        //jQuery... using document ready for safety
        $(document).ready(function() {
    
            var text = $("#mySoapMessage").html(); 
    
        }
    
    </script>
    
    <script id="mySoapMessage">
    
        <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="...">
           <soapenv:Header/>
           <soapenv:Body>
              <typ:getConvocadosElement>
                 ...
              </typ:getConvocadosElement>
           </soapenv:Body>
        </soapenv:Envelope>
    
        <!-- this comment will be present on your string -->
        //uh-oh, javascript comments...  SOAP request will fail 
    
    
    </script>
    
share|improve this answer

to sum up, I have tried 2 approaches listed here in user javascript programming (Opera 11.01):

So I recommend the working approach for Opera user JS users. Unlike what the author was saying:

It doesn't work on firefox or opera; only on IE, chrome and safari.

It DOES work in Opera 11. At least in user JS scripts. Too bad I can't comment on individual answers or upvote the answer, I'd do it immediately. If possible, someone with higher privileges please do it for me.

share|improve this answer
 
This is my first actual comment. I have gained the upvote privilege 2 days ago so so I immediately upvoted the one answer I mentioned above. Thank you to anyone who did upvote my feeble attempt to help. –  Tyler Jul 24 '11 at 12:34
 
Thanks to everyone who actually upvoted this answer: I have now enough privileges to post normal comments! So thanks again. –  Tyler Aug 31 '12 at 2:41

Just tried the Anonymous answer and found there's a little trick here, it doesn't work if there's a space after backslash \
So the following solution doesn't work -

var x = { test:'<?xml version="1.0"?>\ <-- One space here
            <?mso-application progid="Excel.Sheet"?>' 
};

But when space is removed it works -

var x = { test:'<?xml version="1.0"?>\<-- No space here now
          <?mso-application progid="Excel.Sheet"?>' 
};

alert(x.test);​

Hope it helps !!

share|improve this answer
4  
well obviously if you have a space after a backslash, backslash escapes the space. It is supposed to escape linebreak, not space. –  Sejanus Dec 14 '12 at 8:47

I think this workaround should work in IE, Chrome, Firefox, Safari, Opera -

Using jQuery :

<xmp id="unique_id" style="display:none;">
  Some plain text
  Both type of quotes :  " ' " And  ' " '
  JS Code : alert("Hello World");
  HTML Code : <div class="some_class"></div>
</xmp>
<script>
   alert($('#unique_id').html());
</script>

Using Pure Javascript :

<xmp id="unique_id" style="display:none;">
  Some plain text
  Both type of quotes :  " ' " And  ' " '
  JS Code : alert("Hello World");
  HTML Code : <div class="some_class"></div>
</xmp>
<script>
   alert(document.getElementById('unique_id').innerHTML);
</script>

Cheers!!

share|improve this answer
 
<xmp> is so deprecated. It may be allowed in HTML, but should not be used by any authors. See stackoverflow.com/questions/8307846/… –  Bergi Jan 28 at 12:28
 
@Bergi, you are right.. and using <pre>; with escapes wont help in my solution.. I came across similar issue today and trying to figure out a workaround.. but in my case, I found one very n00bish way to fix this issue by putting output in html comments instead of <xmp> or any other tag. lol. I know its not a standard way to do this but I will work on this issue more tomorrow mornin.. Cheers!! –  Aditya Hajare Jan 28 at 13:11

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

My version of array-based join for string concat:

var c = []; //c stands for content
c.push("<div id='thisDiv' style='left:10px'></div>");
c.push("<div onclick='showDo(\'something\');'></div>");
$(body).append(c.join('\n'));

This has worked well for me, especially as I often insert values into the html constructed this way. But it has lots of limitations. Indentation would be nice. Not having to deal with nested quotation marks would be really nice, and just the bulkyness of it bothers me.

Is the .push() to add to the array taking up a lot of time? See this related answer:

(Is there a reason JavaScript developers don't use Array.push()?)

After looking at these (opposing) test runs, it looks like .push() is fine for string arrays which will not likely grow over 100 items - I will avoid it in favor of indexed adds for larger arrays.

share|improve this answer

This works in IE, Safari, Chrome and Firefox:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div class="crazy_idea" thorn_in_my_side='<table  border="0">
                        <tr>
                            <td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
                        </tr>
                    </table>'></div>
<script type="text/javascript">
    alert($(".crazy_idea").attr("thorn_in_my_side"));
</script>
share|improve this answer
2  
Just think about it. Do you think it's valid? Don't you think it can cause display problems? –  Sk8erPeter Feb 24 '12 at 1:55
2  
Why the downvotes? This is a creative answer, if not very practical! –  dotancohen Feb 29 '12 at 2:32
1  
no, it's not. One should rather use templates: $.tmpl() (api.jquery.com/tmpl), or EJS (embeddedjs.com/getting_started.html), etc. One reason for downvotes is that it's really far from a valid code and using this can cause huge display problems. –  Sk8erPeter Mar 24 '12 at 0:07

This works at least in Firefox:

var text = <>
some
multiline
text
</>.toString();
share|improve this answer
4  
 
I confirm it stopped to work, I've 8 GreaseMonkey scripts to update where I used this syntax. –  Dereckson Jan 30 at 12:10

This seems to work in Fx 19 and Chrome 24 on Mac

DEMO

var new_comment; /*<<<EOF 
    <li class="photobooth-comment">
       <span class="username">
          <a href="#">You</a>
       </span>
       <span class="comment-text">
          $text
       </span>
       <span class="comment-time">
          2d
       </span>
    </li>
EOF*/
// note the script tag here is hardcoded as the FIRST tag 
new_comment=document.getElementsByTagName('script')[0].innerHTML.split("EOF")[1]; 
alert(new_comment.replace('$text','Here goes some text'));
share|improve this answer

This is one fairly economical approach, at least in terms of the source code:

function s() {
    var args = [];
    for (var index = 0; index< arguments.length; index++) {
        args.push (arguments [index]);
    }
    return args.join ("\n");
}
console.log (s (
    "This is the first line",
    "and this is the second",
    "finally a third"
));

function s() {return.arguments.join ("\n")} 

would be nicer of course if the "arguments" property were a proper array.

A second version might use "" to do the join for cases when you want to control the line breaks in a very long string.

share|improve this answer

I program this way:

sys = {
    layout: null,
    makeLayout: function (obCLS) {
        this.layout = $('<div />').addClass('editor').appendTo($(obCLS)).append(

            /* Cargador */
            /* @this.layout.find('> div:nth-of-child(1)'); */
            '<div>' +
            '   <p>Seleccione la imagen que desea procesar.</p>' +
            '   <input type="button" value="Seleccionar" class="btn btn-xlarge btn-success" />' +
            '   <span></span>' +
            '</div>' +

            /* Cargador - Progreso */
            /* @this.layout.find('> div:nth-of-child(2)'); */
            '<div>' +
            '   <div>' +
            '       <div></div>' +
            '       <div>' +
            '           <div></div>' +
            '       </div>' +
            '   </div>' +
            '</div>' +

            /* Editor */
            /* @this.layout.find('> div:nth-of-child(3)');
             * @sidebar = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(1)');
             * @body    = this.layout.find('> div:nth-of-child(3) > div > div > div:nth-of-type(2) > div'); */
            '<div>' +
            '   <div>' +
            '       <div>' +
            '           <div></div>' +
            '           <div>' +
            '               <div></div>' +
            '           </div>' +
            '       </div>' +
            '   </div>' +
            '</div>'
        );
    }
}

sys.makeLayout('#div');
share|improve this answer

check this,

Multi-Line JavaScript Strings

See also this performance test from different possibilities; the \ variant is the fastest.

performance test

share|improve this answer

i found a more elegant solution, maybe a little non-topic related because it uses PHP, but im sure it will be useful and cuteness* for some of yours...

this javascript code should stay inside script tags

var html=<?php echo json_encode("

        <div class=container>
            <div class=area1>
                xxx
            </div>
            <div class=area2>
                ".$someVar."
            </div>
        </div>

"); ?>

in your output html you will see something like

var html="\r\n\r\n\t\t\t<div class=container>\r\n\t\t\t\t<div class=area1>\r\n\t\t\t\t\txxx\r\n\t\t\t\t<\/div>\r\n\t\t\t\t<div class=area2>\r\n\t\t\t\t\t44\r\n\t\t\t\t<\/div>\r\n\t\t\t<\/div>\r\n\r\n\t\t";  

 


and et voilà!, it gives you code readability in your file.

pD: this sample uses json_encode() PHP function, but certainly there are function equivalents for ASP, Ruby and JSP langs.

pD: however, this solution have his limitations too, one of them is you cannot use javascript variables inside the encapsulated code.

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
11  
You should use var myString += "Second line \n"; instead. MUCH cleaner. –  Colin Feb 27 at 4:45
 
Actually, you should use myString += "Second line \n"; The var shouldn't be repeated. –  Michael Mior Jul 11 at 14:04
 
use + only for concatenate strings. Not need declare all buffer for each line. Its horrorific. –  WHK Aug 2 at 15:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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