JavaScript HERE-doc or other large-quoting mechanism?

Evan Carroll picture Evan Carroll · Jun 2, 2010 · Viewed 12.2k times · Source

Is there a convenient way to quote a large block of HTML that has both single and double quotes in JavaScript?

Is there anything like a HERE-doc <<EOF, a multi-quote character """, or custom delimiters q{}?

Any creative or inventive solutions to this problem?

Answer

Pointy picture Pointy · Jun 2, 2010

Some people don't like this, so be prepared for scorn and derision, but one trick is to dump your "big block of stuff" into a <script language="text"> block:

<script id='blockOfStuff' language="text">
  Hi this is random stuff
  <h1>Including HTML markup</h1>
  And quotes too, or as one man said, "These are quotes, but
  'these' are quotes too."
</script>

John Resig has used that technique (or that abomination, if you prefer) for examples of his templating mechanism.

You can get at the contents with "innerText" or "innerHTML" as appropriate, or through the services of your favorite framework.

edit — note that via jQuery (contrary to what I said in a comment below) .text() does not work, though I think it should. Use .html() instead.