我有这样的字符串
"Hello {{firstName}}, this is {{senderName}}."
规则
rules = {
firstName: "Alex",
senderName: "Tracy"
}
期望结果
"Hello Alex, this is Tracy."
我希望泛型函数将具有相应规则的任何字符串转换为新字符串。
另一个例子:
let array = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
rules = {
firstName: "Alex",
lastName: "James",
senderName: "Tracy"
}
expectedResult = "Hello Alex James, this is Tracy."
任何帮助伤口都会受到赞赏。
答案 0 :(得分:2)
您可以遍历所有变量并将其替换为值
function resolve_str(rules,str){
for(let i in rules){
str = str.replace("{{"+i+"}}", rules[i]);
}
return str;
}
let array = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
rules = {
firstName: "Alex",
lastName: "James",
senderName: "Tracy"
}
console.log(resolve_str(rules,array));
答案 1 :(得分:1)
您可以利用可以传递给replacement function的String.prototype.replace:
const str = "Hello {{firstName}} {{lastName}}, this is {{senderName}}."
const mapping = {
firstName: "Alex",
lastName: "James",
senderName: "Tracy"
}
const compile = (template, rules) => template.replace(/{{(.+?)}}/g, (match, group) => rules[group]);
const result = compile(str, mapping);
console.log(result);