javascripttemplate-literalstagged-templates

Tag for generic template literal function in javascript


My goal is to write a tagged template function like

myTemplateTagFunction`some text ${variable} etc. etc.`

...that behaves like the default template literal function in javascript.

My first attempt was

let myTaggedTemplate = args => `${args}`

But this breaks pretty quickly...

> myTaggedTemplate`hello world ${2 + 5}`
// "hello world ,"

> `hello world ${2 + 5}`
// "hello world 7"

There must be an easier way to do this that I'm missing?


Solution

  • There's perhaps a shorter way to do it, but this is my approach:

    const myTaggedTemplate = (strings, ...vars) => {
        let result = '';
        strings.forEach((str, i) => {
            result += `${str}${i === strings.length - 1 ? '' : vars[i]}`;
        });
        return result;
    };