JavaScript – Faking Here Document

Nearly a year ago I wrote a quick post about the awesome heredoc notation for strings in many languages such as PHP:

$query = <<<QUERY
SELECT *
FROM table
WHERE col_1 = val_1
  AND col_2 = val_2;
QUERY;

Unfortunately, this doesn’t exist in JavaScript. If for some reason you do need to fake it though, you can use a comment in order to achieve your goal:

function query() {
/*QUERY
SELECT *
FROM table
WHERE col_1 = val_1
  AND col_2 = val_2;
QUERY*/
}

Now that we have our function that does nothing and our interestingly formatted comment we can use the following function:

function getHereDoc(fn) {
  var match = /\/\*(\w+)(\s*?\r?\n)([\s\S]+)\2\s*\1\*\//.exec(fn + '');
  return match && match[3];
}

Now all we have to do is this:

strQuery = getHerDoc(fn);

Now strQuery will contain the query with all of the new-line characters. One downside is that you would need to make sure that you are not using a minifier on functions such as the query function because if you do, the comments will be removed. Another less common shortcoming (unless someone knows a workaround, is the fact that you can’t use */ in the string.

Even though this is a viable solution, I would recommend just using real strings. If you need to turn multiple lines of text into string you can use this:
Multiline JS Stringifer

One thought on “JavaScript – Faking Here Document”

Leave a Reply

Your email address will not be published. Required fields are marked *


nine − = 4

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">