Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

javascript - How to call native es6 template string replacement from tag function?

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

eg.

function dumbTag(strs, ...vals) {
    vals = vals.map((val,i) =>
            (i % 2 == 0 ? 'even:' : 'odd:')+val);
    return String.template(strs, ...vals);
}

my own implemented function - is there a faster way / way to call what the browser does?

function template(strs, ...vals) {
    let result = strs[0];
    for (let [i,val] of vals.entries()) {
        result += val;
        result += strs[i+1];
    }
    return result;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

This is essentially just tricking String.raw into thinking that the escape-interpreted string is the raw version.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...