JavaScript tip of the day: Extending a String Across Multiple Lines

June 17th 2010

I’m working on a project where I need to inject qui a bit of HTML. The examples will feature jQuery but it works with any library as it is simply string handling in javascript.

So the problem we face is that a string of content on a single line is hard to read. Something like that:

$(element).append('<div class="content"><div class="left"></div><div class="right"></div></div>');

It’s really not easy to maintain as you  have to figure out where in the HTML structure you want to add new elements.

So here’s the tip

To keep the HTML cleanly formatted simply add a backslash after every line. This way you escape the new line feed and the javascript thinks everything is on a single line. Here’s an example:

$(element).append(' \
  <div class="content"> \
    <div class="left"> \
    </div> \
    <div class="right"> \
    </div> \
  </div> \

It’s a very nice way to keep the HTML structured to make sure the code is easily maintainable.

Hope you liked it 🙂

10 Responses to “JavaScript tip of the day: Extending a String Across Multiple Lines”

  1. […] This post was mentioned on Twitter by Stephane Caron, Anton Pawlik. Anton Pawlik said: RT @scaron: JavaScript tip of the day: Extending a String Across Multiple Lines […]

  2. Nice to know, thanks for sharing!

  3. I thought it was pretty clever when i found that trick in your PrettyPhoto (or was it PrettyGallery?).

    Nice find.

  4. Hi,
    I used to use that trick, but I found myself in great trouble while I was trying to compress the code with google closure compiler or jsmin.
    I don’t know why, but at the end it gives a whole bunch of errors, so I now stick with this way of writing strings over multiple lines:

    var myString= ‘lorem ipsum ‘+
    ‘lorem ipsum again ‘+
    ‘and again’;


  5. Stephane says:

    @Davide: Never had any problem with compression. I always use jsmin, never compressed with Google closure yet. The only thing is that it don’t compressed the escaped string. No big deal.

  6. I totally agree with everything you have explained. In reality, I browsed through your several other posts and I do think you’re certainly right. Great job with this particular site.

  7. Bookem says:

    Thanks for the backslash tip. I’ll try it next time. I usually try HTML in the sandbox first.

  8. Jeff C says:

    Awesome tip, and just what I needed :). Thank you.

  9. Its like you learn myy mind! You appsar to know a lot about this, such as youu
    wrote the e book in it oor something. I believe that you simply cann do with a feww
    percent to drive the message home a little bit,
    however otherr than that, this is excellent blog. An excellent read.
    I will deefinitely be back.

Leave a Reply