Learn more
Please note that GitHub no longer supports Internet Explorer versions 7 or 8.

We recommend upgrading to the latest Internet Explorer, Google Chrome, or Firefox.

If you are using IE 9 or later, make sure you turn off "Compatibility View".

This repository

Multiline strings in JavaScript

branch: master
Octocat-spinner-32 .editorconfig init
Octocat-spinner-32 .gitattributes init
Octocat-spinner-32 .gitignore init
Octocat-spinner-32 .jshintrc init
Octocat-spinner-32 .travis.yml init
Octocat-spinner-32 bower.json 0.1.0
Octocat-spinner-32 component.json 0.1.0
Octocat-spinner-32 experiment.js init
Octocat-spinner-32 experiment_test.js init
Octocat-spinner-32 multiline.js init
Octocat-spinner-32 package.json 0.1.0
Octocat-spinner-32 readme.md Update readme.md
Octocat-spinner-32 test.js init
readme.md

multiline Build Status

Multiline strings in JavaScript

No more string concatenation or array join!

Note that ES6 will have template string which can be multiline, but time...

Before

var str = '' +
'<!doctype html>' +
'<html>' +
'   <body>' +
'       <h1>Hello world</h1>' +
'   </body>' +
'</html>' +
'';

After

var str = multiline(function(){/*
<!doctype html>
<html>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>
*/});

How

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.

Install

npm

npm install --save multiline

Browser

Compatibility

  • Latest Chrome
  • Firefox >=17
  • Safari >=4
  • Opera >=9
  • Internet Explorer >=6

Make sure to use /*! instead of /* when minifying to prevent the comments from being stripped.

Download manually or with a package-manager.

Bower

bower install --save multiline

Component

component install sindresorhus/multiline

Example

Everything after the first newline and before the last will be returned as seen below:

var str = multiline(function(){/*
<!doctype html>
<html>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>
*/});

console.log(str);

Which outputs:

<!doctype html>
<html>
    <body>
        <h1>Hello world!</h1>
    </body>
</html>

And a real-world use-case.

Experiment

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>Hello world!</h1>
    </body>
</html>
*/);

License

MIT © Sindre Sorhus

Something went wrong with that request. Please try again.