Last Updated: February 25, 2016
·
2.281K
· irakli

Faux Heredocs in Node.js/JS

Working with multi-line, unsafe (containing apostrophes or quotation marks) strings is a major pain-in-the-neck in Javascript. Alas, you often need to do such things, especially when quickly testing something or hacking a prototype together.

DISCLAIMER: don't do this in production code.

The following nifty trick creates a faux "HEREDOC" that seems to work in Node.js. As the original commenter on Stack Overflow points out: you should be careful to use it in any browsers because browsers may break the trick at any time

function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*!?/, "").
      replace(/\*\/[^\/]+$/, "");
}

var tennysonQuote = hereDoc(function() {/*!
  Theirs not to "make" reply,
  Theirs 'not' to reason why,
  Theirs but to do and die
*/});

source: http://stackoverflow.com/a/5571069

Also, it should be noted that CoffeeScript supports "heredoc" equivalent called Block Strings, natively: http://jashkenas.github.io/coffee-script/#strings (if CoffeeScript is something you can tolerate, that is).

1 Response
Add your response

Wow that's fun, thanks for sharing! :)

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside