gpt4 book ai didi

javascript - 将字符串转换为模板字符串

转载 作者:行者123 更新时间:2023-11-28 04:29:32 25 4
gpt4 key购买 nike

是否可以像普通字符串一样创建模板字符串,

let a = "b:${b}";

然后将其转换为模板字符串,

let b = 10;
console.log(a.template()); // b:10

没有evalnew Function等动态代码生成方式?

最佳答案

在我的项目中,我使用 ES6 创建了类似的东西:

String.prototype.interpolate = function(params) {
const names = Object.keys(params);
const vals = Object.values(params);
return new Function(...names, `return \`${this}\`;`)(...vals);
}

const template = 'Example text: ${text}';
const result = template.interpolate({
text: 'Foo Boo'
});
console.log(result);

关于javascript - 将字符串转换为模板字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44734944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com