Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> \
");
like image 560
Janak Avatar asked May 22 '09 05:05

Janak


People also ask

How do I create a multiline string in JavaScript?

There are three ways to create a multiline string in JavaScript. We can use the concatenation operator, a new line character (\n), and template literals. Template literals were introduced in ES6. They also let you add the contents of a variable into a string.

What is `` in JS?

Although single quotes and double quotes are the most popular, we have a 3rd option called Backticks ( `` ). Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes.


2 Answers

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.

like image 154
thomasrutter Avatar answered Oct 02 '22 16:10

thomasrutter


Having html inline like that is bad practice, but if you really want to handle it cleaner, try this:

Place a hidden div on your page with the html you want, and replace the custom params with something like {title}. When calling update, pass yourdiv.innerHTML.replace(...

like image 20
Luke Schafer Avatar answered Sep 28 '22 16:09

Luke Schafer