Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 794
Aaron_H Avatar asked Jul 05 '16 17:07

Aaron_H


People also ask

What is ${} in JavaScript?

It's used to reference a variable within string: let someVar = "World!" console. log(`Hello ${someVar}`); // Output is Hello World!

Can I use backticks JavaScript?

Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes. Besides, using backticks makes it easier for string operations.

What is template string in ES6?

Backtick basics. ES6 introduces a new kind of string literal syntax called template strings . They look like ordinary strings, except using the backtick character ` rather than the usual quote marks ' or " .


1 Answers

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\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.

like image 170
Inkling Avatar answered Sep 29 '22 11:09

Inkling