Multi-line strings

Written by khopesh — Last update Oct 7, 2009

7 points

Using E4X, Firefox supports true multi-line strings in JavaScript; no need for concatenating strings or escaping end-of-lines, just wrap everything in an <r> and CDATA tags:

var the_old_way_1 = "this is a multi-line \
string.\n\
This is its second line.";

/*
this is a multi-line string
This is its second line.
*/

var the_old_way_2 = "this is also a multi-line "
+ "string.\n"
+ "This is its second line.";

/*
this is also a multi-line string.
This is its second line.
*/

var the_E4X_way = "" + (<r><![CDATA[
this is a cleaner multi-line string.
This is its second line.
I can have whatever quotes and tags I like in it, <foo></foo> "hello, I'm quoted."
// this is not a comment!
]]></r>); // this IS a comment.

/*

this is a cleaner multi-line string.
This is its second line.
I can have whatever quotes and tags I like in it, <foo></foo> "hello, I'm quoted."
// this is not a comment!

*/

Note that it important to concatenate this with a string because the E4X is not of the string type by default (and the concatenation will cast it into a string). Another way to accomplish this is to use toString(), like this: var the_E4X_way2 = (<r><![CDATA[ foobar ]]></r>).toString(); You'll also notice that the extra carriage returns between the CDATA's inner-most square brackets are interpreted literally, giving extra lines to your string. You can start your string right away if you like, I just find it easier to have the extra spacing.

Caveats: E4X does not work in Opera or IE, an even vim's syntax highlighting fails to understand what it is without the vim after-syntax for E4X script I wrote.

Example: My Userscripts.org - Face icons, tweaks has almost its entire contents encapsulated in an E4X string. Happily, the syntax highlighting for it isn't so bad (and in vim, I used nested comments to properly highlight everything as CSS).

Scripts mentioned in guide