Tag for generic template literal function in javascript

1.1k views Asked by At

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?

3

There are 3 answers

0
domenikk On BEST ANSWER

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;
};
0
ZORGATI Achraf On

You need to change your function:

let myTaggedTemplate = (strings,...values) => ...;

and try to follow the example in this link

0
Peter Lehnhardt On

How to define a tagged template function

If you define a tagged template function, it has to receive an array of strings as first argument and expressions of arbitrary number as subsequent parameters. The strings are all string between your inserted expressions (between all ${...}) and all expressions are the values of what you put into ${...}.

Example code

let numExp = 2;

function tagFunction(strings, ...expressions) {
  let returnString = "";
  for (let i = 0; i < expressions.length; i++) {
    returnString += strings[i] + expressions[i];
  }
  returnString += strings[strings.length - 1];
  return returnString;
}

console.log(
  tagFunction`Using function \"${tagFunction.name}\" with ${numExp} expressions`
);