js怎么根据key替换字符串的插值
本来想到 es6的 ${} ,但最终取到值,肯定是 ${data.title},由于各种原因在模板字符串中只能 ${title} 去呈现,所以产生了,我这个需求
data:{ title:'发票测试1',
price: 100,
total: 100
}
template: `LODOP.PRINT_INITA(10,10,762,533,"测试")
LODOP.ADD_PRINT_TEXT(38,78,408,30,"{{title}}")
LODOP.ADD_PRINT_TEXT(259,579,100,23,"{{price}}")
LODOP.ADD_PRINT_TEXT(260,520,58,24,"合计:{{total}}")`
=>
`LODOP.PRINT_INITA(10,10,762,533,"测试")
LODOP.ADD_PRINT_TEXT(38,78,408,30,"发票测试1")
LODOP.ADD_PRINT_TEXT(259,579,100,23,"100")
LODOP.ADD_PRINT_TEXT(260,520,58,24,"合计:100")`
回答:
var data = { title: "发票测试1",
price: 100,
total: 100
};
var template = `LODOP.PRINT_INITA(10,10,762,533,"测试")
LODOP.ADD_PRINT_TEXT(38,78,408,30,"{{title}}")
LODOP.ADD_PRINT_TEXT(259,579,100,23,"{{price}}")
LODOP.ADD_PRINT_TEXT(260,520,58,24,"合计:{{total}}")`;
for (let k in data) {
template = template.replace(new RegExp(`{{${k}}}`, "g"), data[k]);
}
console.log(template);
回答:
template.replace(/\{\{(\w+)\}\}/g, (_,key) => data[key])
回答:
function replace(string) { var regex = /\{\{(.+?)\}\}/g;
var replacer = function(match, expr) {
try {
return eval(expr);
} catch(error) {
return data[expr] || "";
}
};
return String.prototype.replace.call(string, regex, replacer);
}
console.dir(replace(
`LODOP.PRINT_INITA(10, 10, 762, 533, "测试")
LODOP.ADD_PRINT_TEXT(38, 78, 408, 30, "{{title}}")
LODOP.ADD_PRINT_TEXT(259, 579, 100, 23, "{{price}}")
LODOP.ADD_PRINT_TEXT(260, 520, 58, 24, "合计:{{total}}")`
));
console.dir(replace(
`LODOP.PRINT_INITA(10, 10, 762, 533, "测试")
LODOP.ADD_PRINT_TEXT(38, 78, 408, 30, "{{data.title}}")
LODOP.ADD_PRINT_TEXT(259, 579, 100, 23, "{{data.price}}")
LODOP.ADD_PRINT_TEXT(260, 520, 58, 24, "合计:{{data.total}}")`
));
回答:
参考:模板字符串 - 带标签的模板字符串
注意使用的时候不是${title}
而是${"title"}
,给的是一个字符串 Key。
function myTemp(strings, ...keys) { return (model) => {
model ??= {};
const parts = [strings[0]];
keys.forEach((key, i) => {
const value = model[key] ?? "";
parts.push(value, strings[i + 1]);
});
return parts.join("");
};
}
const format = myTemp`LODOP.PRINT_INITA(10,10,762,533,"测试")
LODOP.ADD_PRINT_TEXT(38,78,408,30,"${"title"}")
LODOP.ADD_PRINT_TEXT(259,579,100,23,"${"price"}")
LODOP.ADD_PRINT_TEXT(260,520,58,24,"合计:${"total"}")`;
const data = {
title: "发票测试1",
price: 100,
total: 100
};
console.log(format(data));
LODOP.PRINT_INITA(10,10,762,533,"测试")LODOP.ADD_PRINT_TEXT(38,78,408,30,"发票测试1")
LODOP.ADD_PRINT_TEXT(259,579,100,23,"100")
LODOP.ADD_PRINT_TEXT(260,520,58,24,"合计:100")
以上是 js怎么根据key替换字符串的插值 的全部内容, 来源链接: utcz.com/p/937151.html