Multi Line Strings

From GreaseSpot Wiki
Revision as of 17:02, 8 February 2010 by Arantius (talk | contribs) (Created page with 'Sometimes it is desirable to define a multi line string in Javascript. Here's a number of possible aproaches, and discussion about the strengths and weaknesses of each approach. …')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Sometimes it is desirable to define a multi line string in Javascript. Here's a number of possible aproaches, and discussion about the strengths and weaknesses of each approach.

Concatenation

The simplest method:

var longString = "Lorem ipsum dolor sit amet, " +
  "venenatis penatibus etiam. " +
  "Nec purus cras elit nec. " +
  "Elit pharetra hymenaeos. " +
  "Donec at cubilia pulvinar elit. " +
  "Aliquet pretium tortor montes maecenas ante amet vel bibendum.";

Pros:

  • Simple to understand.

Cons:

  • Extra syntax at the head and tail of every line.
  • Javascript string concatenation has poor performance characteristics.

A very similar but more efficient approach would define an array of many strings, then join them into one long string:

var longString = ["Lorem ipsum dolor sit amet, ",
  "venenatis penatibus etiam. ",
  "Nec purus cras elit nec. ",
  "Elit pharetra hymenaeos. ",
  "Donec at cubilia pulvinar elit. ",
  "Aliquet pretium tortor montes maecenas ante amet vel bibendum."
  ].join("");

Line continuation

Javascript can continue lines, via trailing backslashes, like C:

var longString = "Lorem ipsum dolor sit amet, \
  venenatis penatibus etiam. \
  Nec purus cras elit nec. \
  Elit pharetra hymenaeos. \
  Donec at cubilia pulvinar elit. \
  Aliquet pretium tortor montes maecenas ante amet vel bibendum.";

Pros:

  • Efficient.

Cons:

  • An uncommon technique, it is not as well understood.

E4X

The E4X technology allows embedding XML documents directly in Javascript. It can be used to pull out a (potentially long, multi-line) string from a dummy XML document.

var longString = <str><![CDATA[
  Lorem ipsum dolor sit amet,
  venenatis penatibus etiam.
  Nec purus cras elit nec.
  Elit pharetra hymenaeos.
  Donec at cubilia pulvinar elit.
  Aliquet pretium tortor montes maecenas ante amet vel bibendum.
]]></str>.tostring();

Pros:

  • Newlines are preserved in the string.
  • Extra markup is required at neither the beginning nor the end of each line.

Cons:

  • Only somewhat efficient; no string-concatenation issues, but does involve creation and throwaway of an XML DOM.