Code Snippet

Home » Code Snippets » JavaScript » Multiline String Variables in JavaScript

Multiline String Variables in JavaScript

This works:

var htmlString = "<div>This is a string.</div>";

This fails:

var htmlSTring = "<div>
  This is a string.
</div>";

Sometimes this is desirable for readability.

Add backslashes to get it to work:

var htmlSTring = "<div>\
  This is a string.\
</div>";

Subscribe to The Thread

  1. Looks pretty cool. I was looking for a way to do that…

  2. try this

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

  3. NIle

    This also works.
    [code]
    var htmlSTring = ""+
    " This is a string."+
    "";
    [/code]

  4. I really like this way:

    var htmlString = [
    '',
    '',
    ''
    ].join(”);

  5. Fabrizio Calderan

    Looking at this guide (under «Multiline string literals») this syntax don’t seems to be a good practice and it’s not part of ECMAScript (but I admit I like it anyway)

  6. hsablonniere

    Douglas Crockford advise not to use that because if you have a space character after the slash that escapes your multiline string it fails.

    Look at slide 12 : http://www.slideshare.net/douglascrockford/level-7-ecmascript-5-the-new-parts

    Try one of theses techniques : http://jsperf.com/zp-string-concatenation/5

  7. David

    If PHP is available, another option is to parse out the extra white space on the server like so (short tags could be useful here too, but not advised):

    
    var injection = "<?php
    ?><table><?php
        ?><tr><?php
            ?><td>Hello</td><?php
            ?><td>World!</td><?php
        ?></tr><?php
    ?></table>";
    

    I think Fabrizio is right, the escaping trick isn’t supported by the standard.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~