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#
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.
var square = new Function('x','return x*x;');
alert(square(5)); // alerts 25
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).
. 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 JavaScrip
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\