将所有{{var}}替换为值

时间:2017-07-18 09:15:50

标签: javascript regex

我有一个包含标识符的字符串

"Hello {{name}}, you are {{age}} years old."

示例对象:

let valueMap = {name: 'jeff', age: 26}

将此转换为以下内容的最佳方法是:

"Hello jeff, you are 26 years old."

我目前的代码是:

let string = 'Hello {{name}}, {{name}} you are {{age}} years old. {{wtf}}';

let objMap = {
  name: 'deojeff',
  age: 26,
}

let parsedString

let matched = string.match(/[^\{{.+}]+(?=}})/g)

let replaced = string.replace(/[^\{{.+}]+(?=}})/g, (args) => {
  return objMap[args] !== undefined ? objMap[args] : args
})

console.log(replaced) 
// Hello {{deojeff}}, {{deojeff}} you are {{26}} years old. {{wtf}}

但它包含{{ }},最好的方法是什么?

6 个答案:

答案 0 :(得分:2)



var string = 'Hello {{name}}, {{name}} you are {{age}} years old. {{wtf}}';
var objMap = {
  name: 'deojeff',
  age: 26,
};
for (var prop in objMap) {
  if (objMap.hasOwnProperty(prop)) {
    string = string.replace(new RegExp('{{' + prop + '}}', "g"), objMap[prop]);
  }
}
console.log(string);




答案 1 :(得分:1)

有许多模板解析器库可用。你可以使用其中一个。 dot是其中之一,您可以参考here

答案 2 :(得分:0)

只需将替换功能更改为:

let replaced = string.replace(/{{(.*?)}}/g, (args, arg0) => {
  return objMap[arg0] !== undefined ? objMap[arg0] : args
})

答案 3 :(得分:0)

var string = 'Hello {{name}}, {{name}} you are {{age}} years old. {{wtf}}';

var objMap = {
  name: 'deojeff',
  age: 26,
}

var matched = string.match(/[^\{{.+}]+(?=}})/g)

var replaced = string.replace(/(\{{.*?\}})/g, function (m, $1){
      //choping of {{}} from start and end so that we dget key
      var key = $1.slice(2, -2);;
      return objMap[key] || ' ';
  });

console.log(replaced) 
// Hello {{deojeff}}, {{deojeff}} you are {{26}} years old. {{wtf}}

答案 4 :(得分:0)

如果你使用es6,你总是可以反击(模板文字)。

let obj = {
  name: 'deojeff',
  age: 26,
}

let string = `Hello ${name}, ${name} you are ${age} years old.`

console.log(string)

您可以阅读更多here

答案 5 :(得分:0)

这将是有效的。另外,将{{wtf}}替换为



const string = 'Hello {{name}}, {{name}} you are {{age}} years old. {{wtf}}';

const objMap = {
  name: 'deojeff',
  age: 26,
}

// const matched = string.match(/(?:\{{2})([^\}])+(?:\}{2})/g);

const replaced = string.replace(/(?:\{{2})([^\}])+(?:\}{2})/g, (args) => {
  const parsedArgs = args.replace(/\{|\}/g, '');
  return objMap[parsedArgs] !== undefined ? objMap[parsedArgs] : '';
});