Hacker News new | past | comments | ask | show | jobs | submit login

A tagged template literal is just a special ES6 syntax for calling a function with a specific set of arguments. You could pass a function which returns all of the arguments as an array to see what's passed in. Try the following in the console of a modern browser:

    function log(...args) { return args; }
    log `abc ${'blah'} fooo\n ${12+3} bar`;
Or you could even shorten the above down to this:

    ((...args)=>args) `abc ${'blah'} fooo\n ${12+3} bar`;
The expression will evaluate to this:

    [["abc ", " fooo\n ", " bar"], "blah", 15]
The first argument is an array of the parts of the literal text, and then the rest of the arguments are the values that were passed in. Additionally, the first argument (the array of string parts) has the `raw` property set to point to an array of string parts with the backslash escapes uninterpreted.

Here's an example re-implementation of `String.raw`:

    function raw({raw}, ...values) {
      const parts = new Array(raw.length*2-1);
      parts[0] = raw[0];
      for (let i=0, len=values.length; i<len; i++) {
        parts[2*i+1] = values[i];
        parts[2*i+2] = raw[i+1];
      }
      return parts.join('');
    }



Tagged templates look interesting. It's an overlooked feature that not many people know about




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: