Multiline strings in JavaScript

Posted Wed Oct 17, 2007 @ 4:53 PM

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';

Posted to Jovan's Blog by jovan

Posted on Wed Oct 17, 2007 @ 4:53 PM

Filed under: ,


Posted on Wed Oct 17, 2007 @ 4:53 PM
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.
Posted on Wed Oct 17, 2007 @ 4:53 PM
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.
Posted on Wed Oct 17, 2007 @ 4:53 PM
Although this method works it is annoying to have to place the \ at the end of every line. Doing a search I found another method which might interest you. it is again not perfect javascript but it does work.
Posted on Wed Oct 17, 2007 @ 4:53 PM
Forget the haters Jovan. For those of us who use standards to build good applications instead of over-complicated ones, your solution simple and effective.
Posted on Wed Oct 17, 2007 @ 4:53 PM
Note of course that Jonathan's link was actually already linked in the main article... ;) If this isn't standard JavaScript then the bodies that oversee ECMAScript/JavaScript should either make it standard or adopt C#'s @"". Personally, I find multi-line strings very useful. In C#, they make it easier to write and format command-line messages, such as errors, output, or usage; as well as embedded code, like SQL (albeit, not a best practice, but useful on small projects). In JavaScript, it is very useful for embedding things like HTML in JavaScript (in which case, innerHTML is technically also non-standard IIRC...).
Posted on Wed Oct 17, 2007 @ 4:53 PM
I have always known about the backslash in to continue the string. One of those things I soon picked up when I started to learn JS. Maybe it is just an Australian thing :P
Posted on Wed Oct 17, 2007 @ 4:53 PM
Claiming something doesn't follow standards isn't hating -- it's extremely useful. Imagine implementing this technique in a large javascript application throughout your code and then having to revert it once a new browser that adheres to JavaScript spec properly comes out.
Posted on Wed Oct 17, 2007 @ 4:53 PM
I writing widgets for other people's websites. Each widget's .js has bunch of HTML/CSS stuff. So to create them easily and serve them correctly I had to create a small PHP "widget delivery engine" - sort of little proxy for each .js file. My delivery engine allows for multiline strings and "glues" them together in superlong valid string to be sent to browser. This way - they are easy to write and manage at source level - but of course they won't pass Crockford's JSLINT test :)
Posted on Wed Oct 17, 2007 @ 4:53 PM
I ran across a heredoc-like syntax recently for multi-line strings, and it's also unnecessary to escape quotes, unless you double up on them, since it doesn't use quotes to contain the string. I doubt it would look right in these comments, so I'll just point you to a page with an example.
Posted on Wed Oct 17, 2007 @ 4:53 PM
Just a note about the "australian" thing suggested. The backslash multiline string is actually a feature of the almost 40-year old C language when writing complex #define preprocessor directives :-) . It should not be a surprise when so many languages today (incl. Javascript) have borrowed from the C language syntax.
Posted on Wed Oct 17, 2007 @ 4:53 PM

This article is old, but this should be noted for anybody else who may find it via Google:

As of ECMAScript 5, the backslash syntax has been recognized by standards. Hooray for "paving the cowpaths."

Posted on Wed Oct 17, 2007 @ 4:53 PM

What browsers support multi-line JS strings?

Anonymous comments are not allowed. Click here to log in or create an account.