Multiline strings in JavaScript
No more string concatenation or array join!
Note that ES6 will have template string which can be multiline, but time...
var str = '' +
'<!doctype html>' +
'<html>' +
' <body>' +
' <h1>❤ unicorns</h1>' +
' </body>' +
'</html>' +
'';
var str = multiline(function(){/*
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/});
It works by wrapping the text in a block comment, anonymous function, and a function call. The anonymous function is passed into the function call and the contents of the comment extracted.
Even though it's slower than string concat, that shouldn't realistically matter as you can still do 2 million of those a second. Convenience over micro performance always.
$ npm install --save multiline
Everything after the first newline and before the last will be returned as seen below:
var str = multiline(function(){/*
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/});
console.log(str);
Which outputs:
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
And a real-world use-case.
- Latest Chrome
- Firefox >=17
- Safari >=4
- Opera >=9
- Internet Explorer >=6
Even though minifiers strip comments by default there are ways to preserve them:
- Uglify: Use
/*@preserve
instead of/*
and enable thecomments
option - Closure Compiler: Use
/*@preserve
instead of/*
- YUI Compressor: Use
/*!
instead of/*
You also need to add 0
after the comment so it's not removed as dead-code.
The final result would be:
var str = multiline(function(){/*!@preserve
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/0});
Download manually or with a package-manager.
bower install --save multiline
component install sindresorhus/multiline
I've also done an experiment where you don't need the anonymous function. It's too fragile and slow to be practical though.
It generates a callstack and extracts the contents of the comment in the function call.
var str = multiline(/*
<!doctype html>
<html>
<body>
<h1>❤ unicorns</h1>
</body>
</html>
*/);
var str = 'foo\
bar';
This is not a multiline string. It's line-continuation. It doesn't preserve newlines, which is the main reason for wanting multiline strings.
You would need to do the following:
var str = 'foo\n\
bar';
But then you could just as well concatenate:
var str = 'foo\n' +
'bar';
Note that ES6 will have real multiline strings.