JavaScript (ES 5) hack for clean multi-line strings

November 9th, 2013 at 3:40 pm

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’s 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.

Related posts:

  1. Allocating multi-dimensional arrays in C++
  2. lesson for today: caveat in C++ line-reading
  3. Cool hack: creating custom subroutines on-the-fly in Perl
  4. An observation on writing line-processing loop code
  5. Classical inheritance in JavaScript ES5

One Response to “JavaScript (ES 5) hack for clean multi-line strings”

  1. leeightNo Gravatar Says:

    After compress the javascript code, all of the comments were striped.

Leave a Reply

To post code with preserved formatting, enclose it in `backticks` (even multiple lines)