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

Get the senior executive’s handbook of important trends, tips, and strategies to compete and win in the digital economy.

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.



Read this guide to learn everything you need to know about RPA, and how it can help you manage and automate your processes.

Topics:

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}