如何在 iojs 中获取模板字符串的原始版本
how to get the raw version of a template string in iojs
是否可以在 iojs 中获取模板字符串的原始版本?
var s = `foo${1+1}bar`
console.log(s); // foo2bar
在前面的例子中我想得到字符串:foo${1+1}bar
edit1:
我的需要是检测一个模板字符串是否依赖于它的上下文,如果它只是一个可能包含 CR 和 LF
的 'constant' 字符串
Is it possible to get the raw version of a template string in iojs ?
不,不是。不可能获得文字的原始表示,就像在这些情况下无法获得 "raw" 文字一样:
var foo = {[1+1]: 42};
var bar = 1e10;
var baz = "\"42\"";
请注意,术语 "template string" 具有误导性(因为它可能表明您可以通过某种方式获取字符串的原始值(也不是如上所示的情况))。正确的术语是 "template literal".
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
似乎是静态分析工具的工作。例如。可以使用recast解析源码,遍历所有模板字面量
例如,the AST representation of `foo${1+1}bar`
is:
如果这样的AST节点为空expression
属性,那么就知道这个值是常量了
有一种方法可以在运行时确定模板文字是 "static" 还是 "dynamic",但这涉及到更改代码的行为。
您可以使用 tagged 模板。标记模板是传递模板文字的静态和动态部分的函数。
示例:
function foo(template, ...expressions) {
console.log(template, expressions);
}
foo`foo${1+1}bar` // logs (["foo", "bar"], [2]) but returns `undefined`
即如果 foo
仅传递一个参数,则模板文字不包含表达式。但是,foo
还必须将静态部分与动态部分进行插值,并 return 结果(上例中未显示)。
是否可以在 iojs 中获取模板字符串的原始版本?
var s = `foo${1+1}bar`
console.log(s); // foo2bar
在前面的例子中我想得到字符串:foo${1+1}bar
edit1: 我的需要是检测一个模板字符串是否依赖于它的上下文,如果它只是一个可能包含 CR 和 LF
的 'constant' 字符串Is it possible to get the raw version of a template string in iojs ?
不,不是。不可能获得文字的原始表示,就像在这些情况下无法获得 "raw" 文字一样:
var foo = {[1+1]: 42};
var bar = 1e10;
var baz = "\"42\"";
请注意,术语 "template string" 具有误导性(因为它可能表明您可以通过某种方式获取字符串的原始值(也不是如上所示的情况))。正确的术语是 "template literal".
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
似乎是静态分析工具的工作。例如。可以使用recast解析源码,遍历所有模板字面量
例如,the AST representation of `foo${1+1}bar`
is:
如果这样的AST节点为空expression
属性,那么就知道这个值是常量了
有一种方法可以在运行时确定模板文字是 "static" 还是 "dynamic",但这涉及到更改代码的行为。
您可以使用 tagged 模板。标记模板是传递模板文字的静态和动态部分的函数。
示例:
function foo(template, ...expressions) {
console.log(template, expressions);
}
foo`foo${1+1}bar` // logs (["foo", "bar"], [2]) but returns `undefined`
即如果 foo
仅传递一个参数,则模板文字不包含表达式。但是,foo
还必须将静态部分与动态部分进行插值,并 return 结果(上例中未显示)。