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> \
");
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.
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.
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.
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(...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With