Over a million developers have joined DZone.

JavaScript (ES 5) Hack for Clean Multi-line Strings

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

JavaScript lacks convenient syntax for multiline strings (the equivalent of Python’s triple-quotes or Perl’s "here blocks"), unless you consider this convenient:

var s = "\
line one\n\
line two\n\
line 'three'\n";

This is something ECMAScript 6 is rumored to support (along with other pink fairies and unicorns), once it gets published and adopted. But in the meantime, intrepid JavaScript programmers are left out in the dark. Unless you really need this to preserve sanity and are willing to resort to unconventional methods.


var MultiString = function(f) {
  return f.toString().split('\n').slice(1, -1).join('\n');

var ms = MultiString(function() {/**
line one
line two
line 'three'

Yes, it is as horrible as it looks. And yes, it’s sometimes convenient. Naturally, for a couple of 3-line strings I probably wouldn’t bother. But when you need to cleanly embed multiple, long, multi-line strings (templating, anyone?) in your source code, I find this pretty useful.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Eli Bendersky, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}