Grow your CSS skills. Land your dream job.

Last updated on:

Multiline String Variables in JavaScript

This works:

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

This fails:

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

Sometimes this is desirable for readability.

Add backslashes to get it to work:

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


  1. Dor
    Permalink to comment#

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

  2. try this

    <script type="text/javascript" src=""></script>
    <div class="crazy_idea" thorn_in_my_side='<table border="0">
    <td ><span class="mlayouttablecellsdynamic">PACKAGE price $65.00</span></td>
    <script type="text/javascript">

  3. NIle
    Permalink to comment#

    This also works.
    var htmlSTring = “”+
    ” This is a string.”+

  4. Dom
    Permalink to comment#

    I really like this way:

    var htmlString = [


  5. Fabrizio Calderan
    Permalink to comment#

    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
    Permalink to comment#

    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 :

    Try one of theses techniques :

  7. David
    Permalink to comment#

    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

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

  8. Steve
    Permalink to comment#
  9. Wizard of Osch

    I find the following solution pretty nice, when the string comes from PHP.

    var MultiLine = '<?php echo str_replace("\n", "\\n", $the_string);?>'

  10. any help my code :

    i should error to my code :(

    When these folks get on board, the new passenger count is reported to the conductor. Build a string called countMessage that uses numPassengers to say:

    Attention: There are now 3 passengers on the train!

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

<div>Example code</div>

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".