You can create multiline strings in pure JavaScript using a method based on the serialization of functions, which is implementation-dependent. While this method works in most browsers, there’s no guarantee it will continue to work in the future, so use it with caution.
Here’s how you can use this method to create multiline strings:
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
*/});
This method has been tested successfully in several browsers, including IE 4-10, Opera 9.50-12, Safari 4-6, Chrome 1-45, Firefox 17-21, and Rekonq 0.7.0-0.8.0. However, it is not supported in Konqueror 4.7.4.
Be careful with minifiers, as they tend to remove comments. To preserve comments, you can use a comment starting with /*!
(like the one used in the example).
With ES6, you can use backticks for multiline strings, which is a more standard and reliable approach:
let foo = `
bar loves cake
baz loves beer
beer loves people
`;
Additionally, you could create a string prototype method to remove indentation:
String.prototype.removeIndentation = function() {
return this.replace(/^[ \t]+/gm, '');
};
let foo = `
bar loves cake
baz loves beer
beer loves people
`.removeIndentation();
This removeIndentation
method would remove leading spaces and tabs from each line of the string.