This space is available to any ComponentArt employee to write about anything.

Multiline strings in JavaScript


Myth: You can't have a string literal stretch across two lines of text in JavaScript.

Fact: You can have multiline string literals in JavaScript in all browsers.


Multiline (or is it "multi-line"?) strings are a fringe feature of programming languages. They are very rarely needed, so a lot of languages don't support them at all (VB.NET). And even when a language does support them (C#), most programmers are not even aware of that. How often have you seen something like this in real code:
string myStr = @"This is a C#
multiline string
just because I can!";
I think I used that only once. Old "\n" would have worked alright, but in that case the string was very long. Multiline option was much more readable and also gave me a chance to show off my incredibly amazing super knowledge of this marginal feature. It is this very marginality and near-uselessness that makes multiline strings a topic I want to blog about.

Actually, JavaScript, being a tricky little scripting language, has an increased need for multiline strings. Use it in depth and you will need statements like eval, which evaluates a string of code, or this textbook example:

var square = new Function('x','return x*x;');

alert(square(5)); // alerts 25

This is actually a very useful feature of the language. Being able to construct code on the fly is certainly not your run-of-the-mill onclick-change-image JavaScript. But if you get deep into the language, the need for it does arise. Problem is, what if the function you want to create is more complex than x*x?

var factorial = new Function('n',
  'var result=1; for (var i=1; i<=n; i++) result *= i; return result;');

alert(5)); // alerts 120

That works, but man is it ugly. Too hard to read. Multiline strings to the rescue:

var factorial = new Function('n', '\
  var result = 1;            \
  for (var i=1; i<=n; i++)   \
    result *= i;             \
  return result;             \');

alert(factorial(5)); // alerts 120

Yes, that works! And it's exactly the same as the previous piece of code (aside for extra white space to make it more readable).

Simply put, you can use backslash character to ignore end of line in JavaScript strings. This directly contradicts my JavaScript books. For example, David Flanagan's [JavaScript: The Definitive Guide], my JavaScript bible for almost a decade and counting, specifically says: backslash escape cannot be used before a line break to continue a string. This is clearly incorrect. (I am so proud to have found an error in that book, I want to let everyone know.) I tested this technique in all browsers I could think of, and it works in all of them.

I learned this technique from a Google search that turned up some [post on an obscure Australian forum]. How this one guy was the only enlightened individual is still a mystery.

Note that the strings will not contain newline characters, unlike the C# multiline example from the beginning of this post. In particular in JavaScript:

alert('foobar' == 'foo bar'); // false
alert('foobar' == 'foobar');  // true
alert('foobar' == 'foo\
bar');                        // true!

So end of line is simply magically ignored. If you really want to have new line characters, you will have to run something like:

var myStr = 'line one\n\
line two';

Share this post: email it! | bookmark it! | digg it! | reddit!

Posted by: Jovan
Posted: Wednesday, October 17, 2007 4:53 PM


Comments

graffic said:

What you propose it's against the javascript standards. Let me quote the specifications: "A 'LineTerminator' character cannot appear in a string literal, even if preceded by a backslash" So the book was right, and you're are just using javascript implementation hacks that I believe they've become standards by themselves.
# October 24, 2008 2:12 AM

Jovan said:

You are right that it's against the standards, and in that sense a bad idea. But I have been burned by browser standards so many times, that at this point I put much more stock in simply testing whether it works or not. I suppose I shouldn't be a cheerleader for a non-standard technique, but it was so odd I couldn't resist blogging about it.
# October 24, 2008 5:57 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Blogs On This Site
Thoughts on web user interfaces and component development.
Ramblings of a web control developer.
Web.UI news and more
Next weeks guest: A dog and a baby dog!
I'm in your base, killing your dudes.
Absurdity is it's own message.
Musings of an ex Java developer
im in ur page, hackin ur codez
ComponentArt in the Community
... and the program ran happily ever after.

This Blog