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

后端 未结 2 1788
后悔当初
后悔当初 2020-12-03 23:26

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 litera

相关标签:
2条回答
  • 2020-12-03 23:42

    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:

    function template(strs) {
        var result = strs[0];
        for (var i=1; i < strs.length; i++) {
            result += arguments[i];
            result += strs[i];
        }
        return result;
    }
    
    0 讨论(0)
  • 2020-12-03 23:48

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

    0 讨论(0)
提交回复
热议问题