如何从标签函数调用原生 es6 模板字符串替换? [英] How to call native es6 template string replacement from tag function?
问题描述
我正在为模板文字编写一个 es6 标记函数,它首先检查字符串中的条件,如果未找到条件,则仅将模板文字解释为未标记.我很好奇,从我的标签函数中,是否有一种方法可以调用浏览器的本机模板文字函数(我认为它会比我自己实现的函数更快).Bonue:有了这个,就没有机会组合标签,例如 htmlEscape(unindentfoobar
);
I'm writing a es6 tag function for template literals, which first checks a condition in the string and, if the condition isn't found, merely interprets the template literal as if it were untagged. I am curious if, from my tag function, there is a way to call the browser's native template literal function (which I assume would be faster than my own implemented function). Bonue: With this, couldn't there be an opportunity for tag composition, eg htmlEscape(unindentfoobar
);
例如.
function dumbTag(strs, ...vals) {
vals = vals.map((val,i) =>
(i % 2 == 0 ? 'even:' : 'odd:')+val);
return String.template(strs, ...vals);
}
我自己实现的功能 - 有没有更快的方式/方式来调用浏览器的功能?
function template(strs, ...vals) {
let result = strs[0];
for (let [i,val] of vals.entries()) {
result += val;
result += strs[i+1];
}
return result;
}
推荐答案
您可以 (ab) 使用 String.raw
(唯一的内置标签)用于此目的:
You can (ab)use String.raw
(the only built-in tag) for this purpose:
function doNothingTag() {
arguments[0] = { raw: arguments[0] };
return String.raw(...arguments);
}
// Or in a more modern style:
const doNothingTag = (strings, ...rest) => String.raw({ raw: strings }, ...rest);
doNothingTag`It works!`
// "It works!"
doNothingTag`Even
with
escape
sequences!`
// "Even
// with
// escape
// sequences!"
这本质上只是诱使 String.raw
认为转义解释的字符串是原始版本.
This is essentially just tricking String.raw
into thinking that the escape-interpreted string is the raw version.
这篇关于如何从标签函数调用原生 es6 模板字符串替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!