blog.gvm-it.eu
How to: Heredocs in JavaScript

The following code allows you to define multi line strings in your JavaScript code. However, it is not cross-browser compatible - some implementations will return empty strings. So why bother? Because the V8 engine - thus node.js - does support this dirty hack!

Include the following function somewhere in your code:

function heredoc(func) {
	// get function code as string
	var hd = func.toString();
	
	// remove { /* using a regular expression
	hd = hd.replace(/(^.*\{\s*\/\*\s*)/g, '');
	
	// remove */ } using a regular expression
	hd = hd.replace(/(\s*\*\/\s*\}.*)$/g, '');
	
	// return output
	return hd;
}

Define a template like this - note that we use an empty function where we put our heredoc string into a Javascript comment which gets stripped out:

var myTemplate = function() { /*

<html>
	<body>
		<h1>This is a template</h1>
	</body>
</html>

*/ }

Now you can get the heredocs contents using heredoc(myTemplate):

var myHeredocString = heredoc(myTemplate);
console.log(myHeredocString);

// output:

<html>
	<body>
		<h1>This is a template</h1>
	</body>
</html>

Enjoy!

  1. klovadis posted this
Blog comments powered by Disqus