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

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 ${true ? 'works!' : 'fails'}`
// "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.

Leave a Comment