Ivor O’Connor

April 4, 2009

JavaScript: Multi-line Strings

Filed under: heredoc, JavaScript, multi-line strings, string concatenation, Uncategorized — Tags: — ioconnor @ 4:53 pm

Multi-line strings in JavaScript should not be difficult. It’s something everybody needs to do. Like “Here Documents” in bash. With this in mind the following books were scanned:

  1. JavaScript The Definitive Guide, 5th Edition
  2. JavaScript Bible, Sixth Edition
  3. Professional JavaScript
  4. JavaScript For The World Wide Web, 3rd Edition
  5. Ajax Hacks
  6. DOM Scripting
  7. Ajax Design Patterns

For the following terms:

  1. +
  2. +=
  3. \
  4. <<
  5. Concatenat*
  6. Continu*
  7. Here*
  8. Multi*
  9. String*

The best solutions in all those books were:

var string = “blah blah” +
“blah blah”;


var string = “blah blah”;
string += “blah blah”;

I haven’t figured out when to do a web search as opposed to a book search. Sometimes web solutions are horrible and people tend to repeat the same horrible solutions. Searching for the one good answer means looking at the same old bad solutions reiterated ad nausea. However these book solutions were horrible too.
Turning to the web I found several new solutions. I have yet to try them.

update 2009.04.08: I really don’t understand the following. I’m thinking perhaps they meant a div setting the visibility to hidden and the space it uses to zero. Then taking the text out of the div as needed. However what they posted I copied and as you can see it does not make any sense.

<script id=”blah”>
blah blah
blah blah
var string = document.getElementById(”blah”).innerHTML;

Update 2009.04.08: The following sort of works under some browers. But it does not work in enough to be worth the time it takes. There is another variation of this which does away with the ‘().toString();’ by merely including a ‘””+’ that makes it easier to understand:

var string = (<r><![CDATA[
The text string goes here. Since this is a XML CDATA section,
stuff like <> work fine too, even if definitely invalid XML.
However it does not work with IE6 and older browsers.

and the following everywhere works but is ugly:

var string = “blah blah\
blah blah\

Why do the books not contain how to do these simple tasks? You’d think they’d cover the basics. Some of these books have had 5 or 6 editions to get the basics in to them! Maybe when I try them later I’ll discover they don’t work and that’s why they never made it into the books… OR… Doth JavaScript books truly sucketh?

Create a free website or blog at WordPress.com.