What is the best way to have long string literals in Javascript?

Janak picture Janak · May 22, 2009 · Viewed 8.1k times · Source

Possible Duplicate:
Multiline strings in Javascript

In Ruby you can do something like this:

temp = <<-SQLCODE
  select * from users
SQLCODE

This way you have very long string literals in your code without having to escape lots of characters. Is there something similar in JavaScript?

Currently I have JavaScript code like this, and it's driving me nuts...

  new Element.update(lightbox_id, " \
    <div id='overlay' class='overlay' > \
    </div> \
    <div id='lightbox' class='lightbox'> \
      <div class='lightbox_title'> \
        <div class='corner_image' onclick=\"close_lightbox();return false;\"><a href='#'>" + corner_image + "</a></div> \
        <div class='lightboxname' id='lightboxname'>" + title + "</div> \
        <div class='close_image'> \
          <a href='#' onclick=\"close_lightbox();return false;\">Close</a> or Escape key\
        </div> \
      </div> \
      <div id='" + lightbox_content_id + "' class='lightbox_content'>    \
      </div> \
      <script>  \
        watch_for_escape(); \
      </script> \
    </div> \
");

Answer

thomasrutter picture thomasrutter · May 22, 2009

The syntax you are referring to is often known as here-document (or HEREDOC) and no, it is not available in Javascript.

Adding a backslash as you have been doing is the appropriate way to span strings over multiple lines in JavaScript.