javascript 中通用模板文字函数的标签

rob*_*don 4 javascript template-literals tagged-templates

我的目标是编写一个标记模板函数,例如

myTemplateTagFunction`some text ${variable} etc. etc.`
Run Code Online (Sandbox Code Playgroud)

...其行为类似于 javascript 中的默认模板文字函数。

我的第一次尝试是

let myTaggedTemplate = args => `${args}`
Run Code Online (Sandbox Code Playgroud)

但这很快就打破了......

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

> `hello world ${2 + 5}`
// "hello world 7"
Run Code Online (Sandbox Code Playgroud)

一定有一种我缺少的更简单的方法可以做到这一点?

dom*_*ikk 5

也许有更短的方法来做到这一点,但这是我的方法:

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