Javascript heredoc

后端 未结 14 1643
盖世英雄少女心
盖世英雄少女心 2020-12-02 12:55

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

I found this:

heredoc = \'\\
14条回答
  •  无人及你
    2020-12-02 13:22

    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.

提交回复
热议问题