Javascript heredoc

I need something like heredoc in JavaScript. Do you have any ideas for this? I need cross-browser functionality.

I found this:

heredoc = '\
<div>\
    <ul>\
        <li><a href="#zzz">zzz</a></li>\
    </ul>\
</div>';

I think it will work for me. :)


Solution 1:

Try ES6 String Template, you can do something like

var hereDoc = `
This
is
a
Multiple
Line
String
`.trim()


hereDoc == 'This\nis\na\nMultiple\nLine\nString'

=> true

You can use this great feature even in older browsers with TypeScript

Solution 2:

No, unfortunately JavaScript does not support anything like heredoc.

Solution 3:

How about this:

function MyHereDoc(){
/*HERE
<div>
   <p>
      This is written in the HEREDOC, notice the multilines :D.
   </p>
   <p>
      HERE
   </p>
   <p>
      And Here
   </p>
</div>
HERE*/
    var here = "HERE";
    var reobj = new RegExp("/\\*"+here+"\\n[\\s\\S]*?\\n"+here+"\\*/", "m");
    str = reobj.exec(MyHereDoc).toString();
    str = str.replace(new RegExp("/\\*"+here+"\\n",'m'),'').toString();
    return str.replace(new RegExp("\\n"+here+"\\*/",'m'),'').toString();
}

//Usage 
document.write(MyHereDoc());

Just replace "/*HERE" and "HERE*/" with word of choice.

Solution 4:

Building on Zv_oDD's answer, I created a similar function for easier reuse.

Warning: This is a non-standard feature of many JS interpreters, and will probably be removed at some point, but as I'm building a script to be only used in Chrome, I am using it! Do not ever rely on this for client-facing websites!

// Multiline Function String - Nate Ferrero - Public Domain
function heredoc(fn) {
  return fn.toString().match(/\/\*\s*([\s\S]*?)\s*\*\//m)[1];
};

Use:

var txt = heredoc(function () {/*
A test of horrible
Multi-line strings!
*/});

Returns:

"A test of horrible
Multi-line strings!"

Notes:

  1. Text is trimmed on both ends, so any extra whitespace on either end is OK.

Edits:

2/2/2014 - changed to not mess with the Function prototype at all and use the name heredoc instead.

5/26/2017 - updated whitespace to reflect modern coding standards.