Javascript heredoc

后端 未结 14 1587
盖世英雄少女心
盖世英雄少女心 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:20

    I'm posting this version as it avoids the use of regex for something so trivial.

    IMHO regex is an obfuscation that was created as a practical joke amongst perl developers. the rest of the community took them seriously and we now pay the price, decades later. don't use regex, except for backward compatabilty with legacy code. there is no excuse these days to write code that is not immediately human readable and understandable. regex violates this principle on every level.

    I've also added a way to add the result to the current page, not that this was asked for.

    function pretty_css () {
    /*
        pre { color: blue; }
    
    */
    }
    function css_src (css_fn) {
       var css = css_fn.toString();
       css = css.substr(css.indexOf("/*")+2);
       return css.substr(0,css.lastIndexOf("*/")).trim();
    }
    
    function addCss(rule) {
      let css = document.createElement('style');
      css.type = 'text/css';
      if (css.styleSheet) css.styleSheet.cssText = rule; // Support for IE
      else css.appendChild(document.createTextNode(rule)); // Support for the rest
      document.getElementsByTagName("head")[0].appendChild(css);
    }
    
    addCss(css_src(pretty_css));
    
    document.querySelector("pre").innerHTML=css_src(pretty_css);

提交回复
热议问题