使用变量

时间:2016-12-30 22:22:48

标签: javascript

我正在尝试替换所有这些字符串:

'Apples are {{appleColor}}'
'Oranges are {{orangeColor}}'
'My name is {{name}}'

有了这些:

obj = {
  appleColor: 'red',
  orangeColor: 'orange',
  name: 'Todd'
}

提前致谢!

1 个答案:

答案 0 :(得分:4)

使用 String.prototype.replace() 功能与替换回调的简单解决方案:

var str = "'Apples are {{appleColor}}', 'Oranges are {{orangeColor}}', 'My name is {{name}}' ",
    obj = {
        appleColor: 'red',
        orangeColor: 'orange',
        name: 'Todd'
    };

str = str.replace(/{{(\w+)}}/g, function (m, m1) {
  return obj[m1] || m;  
});

console.log(str);