[英]Tag for generic template literal function in javascript [duplicate]
我的目标是编写一个标记的模板函数,如
myTemplateTagFunction`some text ${variable} etc. etc.`
...它的行为类似于 javascript 中的默认模板文字函数。
我的第一次尝试是
let myTaggedTemplate = args => `${args}`
但这很快就崩溃了......
> myTaggedTemplate`hello world ${2 + 5}`
// "hello world ,"
> `hello world ${2 + 5}`
// "hello world 7"
必须有一种更简单的方法来做到这一点,我错过了?
也许有一种更短的方法可以做到,但这是我的方法:
const myTaggedTemplate = (strings, ...vars) => {
let result = '';
strings.forEach((str, i) => {
result += `${str}${i === strings.length - 1 ? '' : vars[i]}`;
});
return result;
};
如果你定义一个带标签的模板函数,它必须接收一个字符串数组作为第一个参数和任意数量的表达式作为后续参数。 字符串是您插入的表达式之间(所有${...}
)的所有字符串,所有表达式都是您放入${...}
。
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` );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.