Javascript 继承人
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4376431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript heredoc
提问by VeroLom
I need something like heredoc in JavaScript. Do you have any ideas for this? I need cross-browser functionality.
我需要像 JavaScript 中的 heredoc 这样的东西。你对此有什么想法吗?我需要跨浏览器功能。
I found this:
我找到了这个:
heredoc = '\
<div>\
<ul>\
<li><a href="#zzz">zzz</a></li>\
</ul>\
</div>';
I think it will work for me. :)
我认为这对我有用。:)
回答by mko
Try ES6 String Template, you can do something like
试试ES6 String Template,你可以做类似的事情
var hereDoc = `
This
is
a
Multiple
Line
String
`.trim()
hereDoc == 'This\nis\na\nMultiple\nLine\nString'
=> true
You can use this great feature today by with 6to5or TypeScript
你今天可以通过6to5或TypeScript使用这个很棒的功能
回答by Andrew Hare
No, unfortunately JavaScript does not support anything like heredoc.
不,不幸的是 JavaScript 不支持 heredoc 之类的东西。
回答by Zv_oDD
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.
只需用选择的词替换“/*HERE”和“HERE*/”。
回答by Nate Ferrero
Building on Zv_oDD's answer, I created a similar function for easier reuse.
基于 Zv_oDD 的回答,我创建了一个类似的函数以便于重用。
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 everrely on this for client-facing websites!
警告:这是许多 JS 解释器的非标准功能,可能会在某个时候被删除,但由于我正在构建一个仅在 Chrome 中使用的脚本,我正在使用它!对于面向客户的网站,永远不要依赖它!
// 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:
笔记:
- 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.
2/2/2014 - 更改为完全不弄乱函数原型,而是使用名称 heredoc。
5/26/2017 - updated whitespace to reflect modern coding standards.
2017 年 5 月 26 日 - 更新了空格以反映现代编码标准。
回答by Dave Stewart
Depending on what flavour of JS/JS engine you're running (SpiderMonkey, AS3) you can simply write inline XML, into which you can place text on multiple lines, like heredoc:
根据您运行的 JS/JS 引擎的风格(SpiderMonkey,AS3),您可以简单地编写内联 XML,您可以在其中放置多行文本,例如 heredoc:
var xml = <xml>
Here
is
some
multiline
text!
</xml>
console.log(xml.toXMLString())
console.log(xml.toString()) // just gets the content
回答by Charlie
ES6 Template Stringshas heredoc feature.
ES6模板字符串具有 heredoc 特性。
You can declare strings enclosed by back-tick (` `) and can be expanded through multiple lines.
您可以声明由反引号 (` `) 括起来的字符串,并且可以通过多行扩展。
var str = `This is my template string...
and is working across lines`;
You can also include expressions inside Template Strings. These are indicated by the Dollar sign and curly braces (${expression}
).
您还可以在模板字符串中包含表达式。这些由美元符号和花括号 ( ${expression}
) 表示。
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"
There are in fact more features such as Tagged Temple Strings and Raw Strings in it. Please find the documentation at
事实上,它还有更多的功能,比如标记的寺庙字符串和原始字符串。请在以下位置找到文档
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings
回答by Andrew Cheong
I feel bad writing a separate answer for merely an extension to @NateFerrero's answer, but I don't feel editing his answer is appropriate either, so please upvote @NateFerrero if this answer was useful to you.
我很遗憾仅为@NateFerrero 的答案的扩展编写单独的答案,但我认为编辑他的答案也不合适,因此,如果此答案对您有用,请给 @NateFerrero 点赞。
tl;dr—For those who wish to use block comments insidetheir heredoc...
tl;dr——对于那些希望在其 heredoc 中使用块注释的人...
I mainly needed Javascript heredocs to store a block of CSS, e.g.
我主要需要 Javascript heredocs 来存储一个 CSS 块,例如
var css = heredoc(function() {/*
/**
* Nuke rounded corners.
*/
body div {
border-top-left-radius: 0 !important;
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
border-bottom-left-radius: 0 !important;
}
*/});
As you can see however, I like to comment my CSS, and unfortunately (as hinted by the syntax highlighting) the first */
ends the overall comment, breaking the heredoc.
然而,正如你所看到的,我喜欢评论我的 CSS,不幸的是(正如语法高亮所暗示的那样)第一个*/
结束了整体评论,打破了heredoc。
For this specific purpose (CSS), my workaround was to add
对于这个特定目的 (CSS),我的解决方法是添加
.replace(/(\/\*[\s\S]*?\*) \//g, '/')
to the chain inside @NateFerrero's heredoc
; in complete form:
到@NateFerrero's 内的链heredoc
;完整形式:
function heredoc (f) {
return f.toString().match(/\/\*\s*([\s\S]*?)\s*\*\//m)[1].replace(/(\/\*[\s\S]*?\*) \//g, '/');
};
and use it by adding a space between the *
and /
for "inner" block comments, like so:
并通过在“内部”块注释*
和之间添加一个空格来使用它/
,如下所示:
var css = heredoc(function() {/*
/**
* Nuke rounded corners.
* /
body div {
border-top-left-radius: 0 !important;
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
border-bottom-left-radius: 0 !important;
}
*/});
The replace
simply finds /* ... * /
and removes the space to make /* ... */
, thereby preserving the heredoc until called.
在replace
简单地找到/* ... * /
并删除的空间,使/* ... */
,从而保持定界符直到调用。
You can of course remove the comments altogether using
您当然可以使用完全删除评论
.replace(/\/\*[\s\S]*?\* \//g, '')
You can also support //
comments if you add them to the chain:
//
如果将评论添加到链中,您还可以支持评论:
.replace(/^\s*\/\/.*$/mg, '')
Also, you can do something other than the single space between *
and /
, like a -
:
此外,您可以在*
and之间做除单个空格以外的其他操作/
,例如-
:
/**
* Nuke rounded corners.
*-/
if you just update the regex appropriately:
如果您只是适当地更新正则表达式:
.replace(/(\/\*[\s\S]*?\*)-\//g, '/')
^
Or maybe you'd like an arbitrary amount of whitespace instead of a single space?
或者您可能想要任意数量的空格而不是单个空格?
.replace(/(\/\*[\s\S]*?\*)\s+\//g, '/')
^^^
回答by Jakob
You could use CoffeeScript, a language that compiles down to JavaScript. The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime.
您可以使用CoffeeScript,这是一种编译为 JavaScript 的语言。代码一对一编译成等价的JS,运行时没有解释。
And of course, it has heredocs:)
当然,它有heredocs:)
回答by Ga1der
ES5 and earlier versions
ES5 及更早版本
(function(){/** some random multi line text here **/}).toString().slice(15,-5);
(function(){/** some random multi line text here **/}).toString().slice(15,-5);
ES6 and later versions
ES6及以后版本
`some random multi line text here`
`some random multi line text here`
result
结果
some random multi line text here
some random multi line text here
回答by Neall
As others have said, ES6 template strings give you most of what traditional heredocs provide.
正如其他人所说,ES6 模板字符串为您提供了传统heredoc 提供的大部分内容。
If you want to go a step further and use a tagged template string, theredoc
is a nice utility function that lets you do this:
如果您想更进一步并使用带标签的模板字符串,这theredoc
是一个不错的实用程序函数,可让您执行以下操作:
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.
`)
}