Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScriptHeredoc_Javascript_Heredoc - Fatal编程技术网

JavaScriptHeredoc

JavaScriptHeredoc,javascript,heredoc,Javascript,Heredoc,我需要像JavaScript中的heredoc这样的东西。你对此有什么想法吗?我需要跨浏览器功能 我发现: heredoc = '\ <div>\ <ul>\ <li><a href="#zzz">zzz</a></li>\ </ul>\ </div>'; herdoc=\ \ \ \ \ '; 我想这对我会有用的。:) 不,不幸的是,JavaScript不支持像h

我需要像JavaScript中的heredoc这样的东西。你对此有什么想法吗?我需要跨浏览器功能

我发现:

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

我想这对我会有用的。:)

不,不幸的是,JavaScript不支持像heredoc这样的任何东西。

您可以使用,一种编译成JavaScript的语言。代码将一对一编译成等价的JS,并且在运行时没有解释


当然,它有:)

这取决于您运行的JS/JS引擎的风格(SpiderMonkey,AS3),您可以简单地编写内联XML,您可以将文本放在多行中,例如:

var xml = <xml>
    Here 
    is 
    some 
    multiline 
    text!
</xml>

console.log(xml.toXMLString())
console.log(xml.toString()) // just gets the content
var-xml=
在这里
是
一些
多行
短信!
console.log(xml.toXMLString())
console.log(xml.toString())//只获取内容
这个怎么样:

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());
函数myherdoc(){
/*这里

这是写在HEREDOC中的,请注意多行:D。

在这里

这里呢

这里*/ var here=“here”; var reobj=new RegExp(“/\\*”+here+”\\n[\\s\\s]*?\\n“+here+“\\*/”,“m”); str=reobj.exec(myherdeoc.toString(); str=str.replace(新的RegExp(“/\\*”+here+“\\n”,'m'),'').toString(); 返回str.replace(new RegExp(“\\n”+here+“\\\*/”,'m'),'').toString(); } //用法 document.write(myherdoc());

只需将“/*HERE”和“HERE*/”替换为所选单词。

基于Zv_oDD的答案,我创建了一个类似的函数,以便于重用

警告:这是许多JS解释器的非标准功能,可能会在某个时候被删除,但由于我正在构建一个只在Chrome中使用的脚本,我正在使用它!对于面向客户的网站,永远不要依赖于此

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

返回:

"A test of horrible
Multi-line strings!"
注:

  • 文本两端都会被修剪,因此两端的任何额外空白都可以
  • 编辑:

    2014年2月2日-更改为完全不干扰功能原型,改用heredoc名称


    2017年5月26日-更新了空格,以反映现代编码标准。

    我觉得写一个单独的答案仅仅是对的扩展很糟糕,但我觉得编辑他的答案也不合适,所以如果这个答案对您有用,请向上投票@NateFerrero

    tl;dr适用于那些希望在其heredoc中使用阻止评论的人。。。 我主要需要JavaScriptHeredocs来存储CSS块,例如

    var css=herdeoc(函数(){/*
    /**
    *核武器圆角。
    */
    身体科{
    边框左上半径:0!重要;
    边框右上角半径:0!重要;
    边框右下半径:0!重要;
    边框左下半径:0!重要;
    }
    */});
    
    但是,正如您所看到的,我喜欢注释我的CSS,不幸的是(正如语法突出显示所暗示的那样),第一个
    */
    结束了整个注释,打破了herdoc


    为此,我的解决方法是添加

    .replace(/(\/\*[\s\s]*?\*)\//g,$1/)
    
    到@NateFerrero's
    herdeoc
    内链;完整形式:

    函数heredoc(f){
    返回f.toString().match(//\/\*\s*([\s\s]*?)\s*\*\//m)[1]。替换(//(\/\*[\s\s]*?\*)\//g,$1/);
    };
    
    并通过在
    *
    /
    之间为“内部”块注释添加一个空格来使用它,如下所示:

    var css=herdeoc(函数(){/*
    /**
    *核武器圆角。
    * /
    身体科{
    边框左上半径:0!重要;
    边框右上角半径:0!重要;
    边框右下半径:0!重要;
    边框左下半径:0!重要;
    }
    */});
    
    replace
    仅查找
    /*…*/
    并删除空间以使
    /**/,从而在调用之前保留heredoc


    当然,您可以使用

    .replace(//\/\*[\s\s]*?\*\//g',)
    
    如果将注释添加到链中,还可以支持注释:

    。替换(/^\s*\/\/.$/mg,”)
    
    此外,您还可以执行一些操作,而不是
    *
    /
    之间的单个空格,例如
    -

        /**
         * Nuke rounded corners.
         *-/
    
    如果您只是适当地更新正则表达式:

    .replace(/(\/\*[\s\s]*?\*)-\//g,$1/)
    ^
    
    或者你想要任意数量的空格而不是一个空格

    .replace(/(\/\*[\s\s]*?\*)\s+\//g,$1/)
    ^^^
    
    您可以使用Sweet.js宏这样添加它

    请注意,此方法使用反勾号作为字符串分隔符:

    let str = macro {
        case {_ $template } => {
            var temp = #{$template}[0];
            var tempString = temp.token.value.raw;
            letstx $newTemp = [makeValue(tempString, #{here})];
            return #{$newTemp}
        }
    }
    
    str `foo bar baz`
    

    尝试使用ES6字符串模板,您可以执行以下操作

    var hereDoc = `
    This
    is
    a
    Multiple
    Line
    String
    `.trim()
    
    
    hereDoc == 'This\nis\na\nMultiple\nLine\nString'
    
    => true
    

    即使在使用

    的较旧浏览器中,您也可以使用此功能。如果您手头有一些html和jQuery,并且字符串是有效的html,这可能很有用:

    <div id="heredoc"><!--heredoc content
    with multiple lines, even 'quotes' or "double quotes",
    beware not to leave any tag open--></div>
    <script>
    var str = (function() {
       var div = jQuery('#heredoc');
       var str = div.html();
       str = str.replace(/^<\!--/, "").toString();
       str = str.replace(/-->$/, "").toString();
       return str;
    })();
    </script>
    
    
    var str=(函数(){
    var div=jQuery('#herdeoc');
    var str=div.html();
    str=str.replace(/^$/,“”)。toString();
    返回str;
    })();
    
    如果文本之间有注释“”,它也可以工作,但文本的一部分可能是可见的。 这是小提琴:

    范例

    var week=true,b=123;
    var q = eval(extractFuncCommentString(function(){/*!
    
    // this is a comment     
    
    
    'select 
    
    / * this
    is a multiline 
    comment * /
    
     a
    ,b  // this is a comment  
    ,c
    from `table`
    where b='+b+' and monthweek="'+(week?'w':'m')+'" 
    //+' where  a=124
    order by a asc
    '
    */},4));
    
    使用缓存:-制作一个简单的模板函数,并保存该函数:(第二次运行速度很快)

    ES6具有heredoc特性

    您可以声明由反勾号(``)括起的字符串,并且可以通过多行展开

    var str = `This is my template string...
    and is working across lines`;
    
    还可以在模板字符串中包含表达式。它们由美元符号和大括号(
    ${expression}
    )表示

    事实上,它还有更多的特性,例如标记的Temple字符串和原始字符串。请在以下网址查找文档:


    正如其他人所说,ES6模板字符串为您提供了传统遗传算法提供的大部分功能

    如果您想更进一步,并使用标记的模板字符串,是一个很好的u
    var week=true,b=123;
    var q = eval(extractFuncCommentString(function(){/*!
    
    // this is a comment     
    
    
    'select 
    
    / * this
    is a multiline 
    comment * /
    
     a
    ,b  // this is a comment  
    ,c
    from `table`
    where b='+b+' and monthweek="'+(week?'w':'m')+'" 
    //+' where  a=124
    order by a asc
    '
    */},4));
    
    var myfunction_sql1;
    function myfunction(week,a){
    
    
        if(!myfunction_sql1) eval('myfunction_sql1=function(week,a){return ('+extractFuncCommentString(function(){/*!
    'select 
    
    / * this
    is a multiline 
    comment * /
    
     a
    ,b  // this is a comment  
    ,c
    from `table`
    where b='+b+' and monthweek="'+(week?'w':'m')+'" 
    //+' where  a=124
    order by a asc
    
    '*/},4)+')}');
        q=myfunction_sql1(week,a);
        console.log(q)
    }
    myfunction(true,1234)
    
    var str = `This is my template string...
    and is working across lines`;
    
    var js = "Java Script";
    var des = `Template strings can now be used in ${js} with lot of additional features`;
    
    console.log(des); //"Template strings can now be used in Java Script with lot of additional features"
    
    if (yourCodeIsIndented) {
      console.log(theredoc`
        Theredoc will strip the
        same amount of indentation
        from each line.
    
          You can still indent
          further if you want.
    
        It will also chop off the
        whitespace-only first and
        last lines.
      `)
    }
    
    (function(){/**
    some random
    multi line
    text here
    **/}).toString().slice(15,-5);
    
    `some random
    multi line
    text here`
    
    some random
    multi line
    text here