Know your ISP.

User #80562   1157 posts
Whirlpool Enthusiast

I ask a hard question so in return, I offer a present :-)

Multiline string literals are one of those things that is broken/missing in Javascript compared to other languages like C, PHP, Perl, etc... Sure you can concatenate a series of partial strings with + over multiple lines, but it's not very elegant, is it?

If your browser supports E4X (XML goodness in Javascript) you can leverage it to have real multiline strings in your Javascript code. Basically you just inline an XML fragment which contains a CDATA node, which in turn contains your multiline string. You then stringify that XML fragment... behold:

  var myString = ""+<r><![CDATA[
      <div class="pmcb_top">
        <div class="pmcb_tabs">
          <ul>
            <li>Chat</li>
            <li>Monks'n'stuff</li>­
            <li>Other</li>
          </ul>
        </div>
      </div>
  ]]></r>;


Yes... that works. (You can't have the CDATA node by itself, you need a wrapper element to trigger the E4X parser.)

I have a bigger example on my perlmonks public scratchpad.

posted 2006-Mar-11, 2am AEST
edited 2006-Mar-11, 2am AEST
User #80562   1157 posts
Whirlpool Enthusiast

Any got any other ways?
Perhaps ways that do not rely on E4X ?

posted 2006-Mar-11, 4pm AEST
User #44690   11005 posts
Whirlpool Forums Addict

How about:

var s = "\
line 1\n\
line 2\n\
";

Not as clean as a heredoc, but still better than string concatenation.

posted 2006-Mar-11, 5pm AEST
User #15538   10847 posts
Whirlpool Forums Addict

You bloody legend, I went to google and found the answer on Whirlpool! I've been pulling my hair out over this one.

posted 2006-Jun-26, 5pm AEST
User #15538   10847 posts
Whirlpool Forums Addict

erroneousBollock, did you get this to work in IE6 at all?

posted 2006-Jun-30, 5pm AEST
Hosted by
WebCentral Australia
Big numbers
975,820 threads
17,201,222 posts
2,008,266 whims sent
3,081 wiki topics
235 ISPs listed
8,129 broadband plans
824 modems & routers
40,569 features filled