9 ms·
Multiline strings in JavaScript
- PavlovsCat 12y agoI thank you from the bottom of my heart. This drove me crazy when playing around with WebGL and shaders, because for various reasons I didn't want to put those in separate files.
- waynecochran 12y agoWhy aren't you just doing this, for example? <script id="fragment" type="x-shader"> precision highp float; uniform vec3 glyphColor; void main() { gl_FragColor = vec4(glyphColor, 1.0); } </script>
- PavlovsCat 12y agoBecause you can't do that from within javascript, and my HTML was really just a stub to load all the javascript I didn't want to have to otherwise deal with.
- abrkn 12y agoYep, I could use this: http://i.gyazo.com/7826deb9e267f52e1f6b4f1afcfb8c4e.png http://i.gyazo.com/7826deb9e267f52e1f6b4f1afcfb8c4e.png
- martin-adams 12y agoInteresting solution. I usually find this type of problem when doing templating in the client when updating things via Ajax. I either use the DOM to store the template or end up concatenating for smaller things. Since to preserve these comments in minification requires conscious effort, I wonder if there's an alternative that could convert the comments to regular JS before minification. Obviously you can't just run it in Node as normal doing it this way.
- ttty 12y agoThe first problem I see, is using any build process which will remove all the comments. Therefore your string will become ''. I wonder how to avoid this.
- mofle 12y agoIt's mainly intended for use in Node.js, but I've documented how to use it with a minifier for the front-end: https://github.com/sindresorhus/multiline#minification https://github.com/sindresorhus/multiline#minification
- criswell 12y agoThere's a section on minification here: https://github.com/sindresorhus/multiline#minification https://github.com/sindresorhus/multiline#minification
- mappum 12y agoThat's a really smart hack, I didn't realize comments were included in the output of Function#toString. You could do other cool things, e.g. an annotation for type checking: function checkType(f) { return function(a) { var type = f.toString().match(/\/\/(.*)\n/)[1].trim(); if(type !== typeof(a)) throw new Error('Invalid type'); return f(a); } } var halve = checkType(function(n) { // number return n / 2; }); halve(4); // returns 2 halve('string'); // emits error
- tlrobinson 12y agoI didn't realize comments were included in the output of Function#toString Probably because sometimes they're not, depending on the JavaScript engine (though perhaps all of the major modern browsers do)
- mofle 12y agoThe following browsers return comments: - Latest Chrome - Firefox >=17 - Safari >=4 - Opera >=9 - Internet Explorer >=6 From: https://github.com/sindresorhus/multiline#compatibility https://github.com/sindresorhus/multiline#compatibility
- coldtea 12y agoNot just "Latest Chrome". Chrome has been doing it for at least 2 years. I know, because I'm using it with it.
- chrishawes 12y agoThis is really handy for DFP creative templates. Thank you.
- adrusi 12y agoWhen I was first really to program I was into hacking javascript to do the crazy things I wanted it to do. I basically did exactly this, albeit with a worse interpolation feature[1]. Don't actually do this please. In the browser, just open up a different <script type="text/plain"> and grab the string from that tag. On the server you can just use a file. Any string that's actually long enough for `["foo", "bar"].join("\n")` to be too cumbersome should be in a separate file, especially if the other way involves a massive hack. [1]: http://zurb.com/forrst/posts/Javascript_native_multi_line_string-gBE http://zurb.com/forrst/posts/Javascript_native_multi_line_st...
- igl 12y agoI think i saw 8 libraries before who abused comments like this. Edit: Yawn.
- wldlyinaccurate 12y agoProbably worth pointing out that this won't play nice with most minification utilities unless you don't mind leaving all comments in the output. I think for this reason I still prefer using Array.prototype.join for multiline strings: var str = [ '<!doctype html>', '<html>', '<body>', '<h1>❤ unicorns</h1>', '</body>', '</html>', ].join('');
- mofle 12y agoYou can use the `/*@preserve` directive. See: https://github.com/sindresorhus/multiline#minification https://github.com/sindresorhus/multiline#minification
- wldlyinaccurate 12y agoHey, thanks - that'll teach me for not reading the full page!
- gravity13 12y agoYou can also var str = ' \ <!doctype html> \ <html> \ <body> \ <h1>❤ unicorns</h1> \ </body> \ </html> \ ' I find it's better than string concat because the trailing \ is just one annoying thing rather than three.
- tekacs 12y ago... also this is (presumably) 'joined' at parse time, rather than runtime (and so only once per execution, guaranteed).
- jaredmcateer 12y ago6 months later: var str = ' \ <!doctype html> \ <html> \ <body> \ <h1>❤ unicorns</h1> \ </body> \ </html> \ ' Help I'm maintaining your code and I get a syntax error
- tlrobinson 12y agoFYI, CoffeeScript has multiline strings (and a bunch of other nice things!)
- mushishi 12y agoSorry but what does this have to do with anything?
- tlrobinson 12y agoIf you want niceties like multiline strings, CoffeeScript is a better option than clever hacks like this. var str = multiline(function(){/*!@preserve multi line string */console.log}); Really?
- mushishi 12y agoWell, I don't get what is the point of suggesting alternative languages that have multiline strings when we are talking about one specific language. The topic is about how to do multiline string in Javascript in one way, and one alternative is not to use multiline strings in Javascript. It's kinda big jump from the original purpose of the topic to start suggesting alternative languages... if we are to be this slack, then we can start spamming most threads with weakly related stuff. For example, you can easily advertise coffeescript in each and every javascript thread in a similar way you did in this specific thread but do we really need want that?
- asdfologist 12y agoI do. I love learning about closely related topics while reading the comments.
- nottombrown 12y agoCoffeescript is just javascript with syntactic sugar on top. This library provides sugar for multiline strings.
- andrelaszlo 12y agoThis snippet does the same thing, mostly: var multiline = function(){/* foo bar baz */}.toSource().match(/\/\*([\s\S]*)\*\//)[1].trim()
- mofle 12y agoYeah, pretty much, but in Node we wrap repetitive things in modules, as they're super cheap. Your snippet is also missing some things like indentation stripping, error handling and browser support.
- dsego 12y agoWhy not a pre-processor?
- mofle 12y agoIn Node.js you don't want a compile step. In the browser however that would probably be a better solution indeed.
- alextgordon 12y agoWhy don't you want a compile step?
- mofle 12y agoBecause a compile step is annoying when it's not strictly needed. In the browser you usually have some kind of build system for concatenation and minifying anyways.
- knubie 12y agoWith coffeescript, at least, there is no extra compile step from the user's point of view. You can run `coffee myapp.coffee` in the same way you would run `node myapp.js`
- aikah 12y agono compile step needed in nodejs. Most third party languages can hack require so using the transpiled language requires no manual compilation.
- evilpie 12y ago>Note that ES6 will have template string which can be multiline, but time... Firefox Nightly currently supports just enough of template strings to give you multiline strings.
- Excavator 12y agoSince a couple weeks back templating is also implemented¹, just lacking tagged templates and documentation²³. 1: https://bugzilla.mozilla.org/show_bug.cgi?id=688857#c22 https://bugzilla.mozilla.org/show_bug.cgi?id=688857#c22 2: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... 3: https://developer.mozilla.org/en-US/docs/Web/JavaScript/ECMAScript_6_support_in_Mozilla https://developer.mozilla.org/en-US/docs/Web/JavaScript/ECMA...
- teddyh 12y agoToday I learned that in JavaScript, comments are significant and part of the code. (And people complain about Python having significant whitespace?)
- Kiro 12y agoOnly significant if you want it to be.
- cyphunk 12y agoseriously? you people be nuts http://stackoverflow.com/a/15558082/2371924 var myString = function(){/* multi-line string */}.toString().slice(14,-3) take this code snippet, throw a package.json and some yaml in and make another npm to Show HN.
- coldtea 12y agoYeah, only it does several other things do. Like optionally removing indend whitespace. Did you even read TFA?
- ricardobeat 12y agoBe sure to scroll to the bottom for a real-world example, this is very brittle.
- jgillich 12y agoI just use ES6 template strings together with the es6ify transform for Browserify. Works in all browsers and very likely performs much better than using Function.prototype.toString.
- mattdesl 12y agoCool hack, but a cleaner solution would be to just use fs.readFileSync if you really want long strings, and let browserify/brfs to inline it for you in the browser. Using this in a library would be pretty unsafe, given how it's browser-dependent, is prone to issues with minifcation, and could just break with future versions of your JS engine.
- VeejayRampay 12y agoIn other news, the ubiquitous language of the ubiquitous platform of the information age doesn't support multiline strings. But I guess if we keep throwing enough modules and libraries at it, it'll end up being nice to develop for. Alternatively wait for ES6 or ES7 to (maybe) solve the problem.
- deleted 12y ago[deleted]
- tfb 12y agoWeird... I just just randomly looking at this a few days ago upon a search for "js multiline" when wondering about the common way to spell multiline (multi line vs multi-line vs multiline). I was intrigued by his code though, ultimately in awe of the cleverness and conciseness of it. Very cool hack! Crazy coincidence to see the very code on HN only a few days later.
- jasonkostempski 12y agoCool hack but not supporting multiline strings is a feature as far as I'm concerned. Everyone seems to agree that HTML shouldn't contain JavaScript, why should JavaScript contain HTML?
- biscarch 12y agoThat is actually currently being contested by React and .jsx. That said, I've seen multiline abused for writing SQL queries as well, which would have been better off being written in a separate .SQL file and `fs.read` into a string with a descriptive var name. (Ignoring that massive SQL strings is a code smell imo).
- siculars 12y agoExcept if your application generates dynamic queries. And not of the sort where variables in the WHERE clause are dynamically evaluated. Of the sort where the entire structure of your SQL is dynamically driven by user interaction with your application.
- biscarch 12y agoAre you saying that large SQL strings isn't a code smell if the application is dynamically putting them together? That seems like DSL/Query Builder territory to me. Perhaps you could share an example?
- eob 12y agoAt one point the E4X standard (back in 2007?) enabled a cool multi-line string hack by promoting XML elements to language entities. You could say: var htmlFragment = "" + (<r><![CDATA[ l(a le af fa ll s) one l iness - e.e. cummings ; ]]></r>); And then `htmlFragment` would contain your multi-line string. (The addition with the empty string coerces the <r> element to output its `toString()` value, which happens to be the innerHTML). This is largely a historical factoid, though. I don't think browsers beyond Mozilla ended up supporting E4X. Really clever hack with the function's toString method!
- tach4n 12y agoWouldn't something like a Sweet.js macro be better for this? Just have it output a string with '\n\' at the end of lines, or using Array.join() or whatever you like.
- robgibbons 12y agoThis is a very clever hack. Great use of anonymous functions and toString.
- z3t4 12y agoIf you do multi line strings you could probably do it in a smarter way. Examples: appendChild instead of innerHTML .html file instead of html inside a .js file. .css file instead of css inside a .js file. It can get very messy if you store "data" inside JS. Especially if you store markup or styling in the JS.