Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

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.

http://eli.thegreenplace.net/wp-content/uploads/2013/11/meme-hack.jpg

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.



Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}