Tuesday, May 3, 2011

Multiline strings in Javascript

Sorry, can't seem to find the syntax. Trying to look for the equivalent of

text = <<"HERE" This Is A Multiline String HERE

[from Ruby] in Javscript

From stackoverflow
  • You can do this

    var string = 'This is ' +
    'multiline' + 

    You can also do it like this. According to kooiinc, it doesn't work in IE, so it's quite useless...

    var myString = ""+<r><![CDATA[
          <div id="example">
              <p>Awesome multiline string!</p>
    Itay Moav : You learn something new everyday
    Jordan S. Jones : Forgive my ignorance, but with's with the
    alex : is just an xml fragment, and the CDATA is the node.
    Anonymous : So this only applies in a valid XHTML document, or what?
    KooiInc : As far as I know the second example will only work in Firefox
    alex : I edited my answer, thanks.
    Matthew Crumley : The second example is using E4X, which is why it only works in Firefox. It does work fine in either HTML or XHTML though. The part could be anything (even empty: <>).
  • Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:

    "foo \
    staticsan : Be warned: some browsers will insert newlines at the continuance, some will not.
  • the pattern text = <<"HERE" This Is A Multiline String HERE is not available in js (I remember using it much in my good old Perl days).

    To keep oversight with complex or long multiline strings I sometimes use an array pattern:

    var myString = 
       ['<div id="someId">',
        'some content<br />',
        '<a href="#someRef">someRefTxt</a>',

    or the pattern anonymouos already showed (escape newline), which can be an ugly block in your code:

        var myString = 
           '<div id="someId"> \
    some content<br /> \
    <a href="#someRef">someRefTxt</a> \
  • i tried all above items ...but did not work in IE... anybody able to work multiline string with java script in IE (IE6/7)

    annakata : No, it can't be done. OTOH it's not exactly essential.


Post a Comment