如何在iojs中获取模板字符串的原始版本
是否可以在IOJS中获得模板字符串的原始版本?
var s = `foo${1+1}bar`
console.log(s); // foo2bar
在上一个示例中,我想获得字符串:foo $ {1+1} bar
edif> edit1 : 我的需要是检测模板字符串是否取决于其是否仅是一个可能包含CR和LF的“常数”字符串
Is it possible to get the raw version of a template string in iojs ?
var s = `foo${1+1}bar`
console.log(s); // foo2bar
In the previous example I would like to get the string: foo${1+1}bar
edit1:
My need is to detect whether a template string depends on its context of if is is just a 'constant' string that may contain CR and LF
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,不是。不可能获得文字的原始表示形式,就像在这些情况下没有办法获得“原始”字面意思:
请注意一词“模板字符串”是误导的(因为这可能表明您可以以某种方式获得字符串的原始值(这也不是上面所示的情况))。正确的术语是字面意思”。
这似乎是静态分析工具的工作。例如,您可以使用 recast 来解析源代码并穿越所有模板文字。
例如,
代码>是
:
如果这样的AST节点为一个空的
expression 属性,然后您知道该值是恒定的。
有一种方法可以确定模板在运行时是“静态”还是“动态”,但这涉及更改代码的行为。
您可以使用标记模板。标记的模板是通过模板字面的静态和动态部分传递的函数。
示例:
IE如果
foo
仅通过一个参数,则模板文字不包含表达式。但是,foo
还必须用动态零件插入静态零件并返回结果(未在上面的示例中显示)。No it is not. It's not possible to get the raw representation of the literal, just like there is no way to get the "raw" literal in these cases:
Note that the term "template string" is misleading (as it may indicate that you could somehow get the raw value of the string (which is also not the case as shown above)). The correct term is "template literal".
Seems like a job for a static analysis tool. E.g. you can use recast to parse the source code and traverse all template literals.
For example, the AST representation of
`foo${1+1}bar`
is:If such an AST node as an empty
expression
property, then you know that the value is constant.There is a way to determine whether a template literal is "static" or "dynamic" at runtime, but that involves changing the behavior of the code.
You can use tagged templates. Tagged templates are functions that get passed the static and dynamic portions of a template literal.
Example:
I.e. if
foo
gets passed only a single argument, the template literal does not contain expressions. However,foo
would also have to interpolate the static parts with the dynamic parts and return the result (not shown in the above example).