Multi-line strings in Javascript

For reference in case I lose it later. Thanks to E4X, we can now have multi-line strings similar to HEREDOC syntax (although quite a bit more verbose):

  var string = (<r><![CDATA[

     The text string goes here.  Since this is a XML CDATA section,
     stuff like <> work fine too, even if definitely invalid XML.

  ]]></r>).toString();

This syntax works fine on Greasemonkey too (trunk, 2005-10-ish, GM 0.6.3). Should be useful, especially in combination with stuff like the add CSS “pattern”…

I can’t believe how much pain it is to try to get raw text in here… This is just a bit silly. Basically had to go turn off the WYSIWYG editor cocmpletely. I guess I should try doing things in an external editor instead…

11 Responses to “Multi-line strings in Javascript”

  1. dougmccune.com » Blog Archive » Multi-line strings in Actionscript 3 Says:

    [...] Javascript 2, so maybe some JS guys had figured this one out. Turns out they did. Here’s the JS nugget that led me to my [...]

  2. Tony Says:

    Do you know any other ways which work with IE6,7 ?

  3. mook Says:

    Sorry, no ideas there. IE6 is old enough that if there had been a way, I’d assume smarter people would have found it :)

  4. Molla Says:

    I used something like follows and it works both in IE and FF.

    …. more content

    var page = document.getElementById(”page_html”).innerHTML;
    document.write(page);

  5. Molla Says:

    Sorry, code should be like:

    .... more content

    var page = document.getElementById("page_html").innerHTML;
    document.write(page);

  6. molla Says:

    <script id=”page_html”>
    <html>
    <body>
    There is some content
    </body>
    </html>
    </script>
    <script>
    var page = document.getElementById(”page_html”).innerHTML;
    document.write(new_page);
    </script>

  7. steve Says:

    it doesn’t work in IE though :-(

    Anybody got something similar for IE?

  8. Greasemonkey Tips - graysky Says:

    [...] ECMAScript for XML (E4X) you can simulate HEREDOC in Javascript which is great when blasting HTML or CSS. Having to escape strings and join multi-line strings is [...]

  9. JS_newbie Says:

    Incredible, this is just what i looked for.

  10. Lev Says:

    That should be fine:

    There is some content

    Here is the content above duplicated via JS:

    var page = document.getElementById(”page_html”).innerHTML;
    document.write(new_page);

  11. Lev Says:

    Sorry, html tags were filtered out by wordpress in previous comment.

    That should be fine:

    <html>
    <body>
    <div id=’page_html’>
    There is some content
    </div>
    Here is the content above duplicated via JS:
    <script type=’text/javascript’>
    var page = document.getElementById(”page_html”).innerHTML;
    document.write(new_page);
    </script>
    </body>
    </html>

Leave a Reply