how to get the raw version of a template string in iojs

混江龙づ霸主 提交于 2019-12-11 10:30:25

问题


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


回答1:


Is it possible to get the raw version of a template string in iojs ?

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:

var foo = {[1+1]: 42};
var bar = 1e10;
var baz = "\"42\"";

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".

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

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:

function foo(template, ...expressions) {
    console.log(template, expressions);
}

foo`foo${1+1}bar` // logs (["foo", "bar"], [2]) but returns `undefined`

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).



来源:https://stackoverflow.com/questions/31293928/how-to-get-the-raw-version-of-a-template-string-in-iojs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!