根据规则替换字符串中的单词

时间:2019-02-05 05:53:55

标签: typescript

我有这样的字符串

"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." 

任何帮助伤口都会受到赞赏。

2 个答案:

答案 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 functionString.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);