Multiline Strings in JavaScript
The ability to write multiline strings is a common feature in many languages. It promotes readability and is often much cleaner than the alternatives. Here's a typically ugly example of string concatenation in PHP:
Thankfully, PHP has the benefit of heredoc syntax, which makes code like this much easier to read, write and maintain:
E4X
But what about JavaScript? There is no native heredoc support, but there are some other workarounds that can be used. The first I'll offer up is ECMAScript for XML (E4X).
The first line in the above example is a bit confusing. The XML will return an xml object by default, but what we want is a String. We can type the return as a String by concatenating to an empty string ('').
Next, an element must be wrapped around the CDATA to trigger the XML parser. This step is similar to PHP's heredoc syntax in that it requires an identical beginning and ending identifier.
You can test this yourself in the lab. Currently, it looks like only Gecko browsers (such as Firefox and Camino) support E4X. This obviously doesn't include Internet Explorer, which is (unfortunately) often a large portion of most websites' user bases. While this workaround is interesting, it's definitely not realistic to assume all of your users are using Firefox, despite its rising popularity (also, it will fail to validate).
Hidden Element Hack
Another workaround I've seen is to place the string inside of an element (often hidden from view) and to read it in via JavaScript. Here's an example:
This solution is clever, but definitely a hack job: not very clean, and with a bad accessibility case. The primary issue though is that it doesn't completely solve the problem. Markup is needed to interact with the JavaScript code, so to use this solution one couldn't maintain a completely independent .js file.
Escaping linebreaks
Another solution is very simply just to escape line breaks:
By escaping the linebreak, you're free to continue the string on the next line (note: this doesn't include spaces, so if you want to separate words, you'll need to begin each new line with a space). This solution is not as attractive as the E4X workaround, but has the benefit of being perfectly cross-browser compatible. Therefore, it looks like it's currently the best method available.
Do you know of any other workarounds? If so, please let me know in the comments section.
Escaping linebreaks is a pretty bad idea, imo. If you have a trailing space after the \, then it’s a syntax error.
These two methods work, too:
['this string',
'spans multiple',
'lines'].join(’\n’);
‘this string\n’ +
’spans multiple\n’ +
‘lines’
The second one is better because the yuicompressor will be smart enough to squish it all into a single string literal, so you don’t have the run-time overhead of the join operation.