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


1 Comment

JavaScript Snippet – Get Function Comments | Chris West's Blog · August 29, 2014 at 2:36 PM

[…] year I wrote about having heredoc like strings available in JavaScript. Today I figured i’d briefly bring the topic back, providing a solution for returning an […]

Leave a Reply

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