Skip to content Skip to sidebar Skip to footer

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 i

Solution 1:

You can (ab)use String.raw (the only built-in tag) for this purpose:

functiondoNothingTag() {
  arguments[0] = { raw: arguments[0] };
  returnString.raw(...arguments);
}

// Or in a more modern style:constdoNothingTag = (strings, ...rest) => String.raw({ raw: strings }, ...rest);

doNothingTag`It works!`// "It works!"

doNothingTag`Even\nwith\nescape\nsequences!`// "Even// with// escape// sequences!"

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

Solution 2:

There is no such builtin function - untagged template literals are just evaluated straight to strings.

is there a faster way?

That depends a lot on the implementation. In case you are using a transpiler, I would avoid using rest parameters, iterators and for of loops:

functiontemplate(strs) {
    var result = strs[0];
    for (var i=1; i < strs.length; i++) {
        result += arguments[i];
        result += strs[i];
    }
    return result;
}

Solution 3:

I was also wondering if there is such a native function. In the meantime, this is what I use:

consttag = ([head, ...tail], ...args) => tail.reduce((a, b, i) => a + args[i] + b, head);

Solution 4:

A short implementation could be done by using Array.prototype.flatMap() like this:

constdefaultTag = (strs, ...vals) =>
  strs.flatMap((x, i) => [x, i < vals.length ? vals[i] : undefined]).join('');

const name = 'Some name';
const age = 32;

console.log(defaultTag`Hi my name is ${name}, and I'm ${age} years old!`);

Post a Comment for "How To Call Native Es6 Template String Replacement From Tag Function?"