I have the following string `a+b*c` and json :
{
a: 'hello',
b: 'hello2',
c: 'hello3'.
}
我想替换字符串中的字母,以便最后的字符串是
hello+hello2*hello3
。
Js或lodash中有没有简单的方法可以做到这一点?
答案 0 :(得分:1)
将字符串拆分为数组,然后迭代数组以从相应的对象属性构建新字符串
var str = 'a+b*c',
params = str.split(''),
data = {
a: 'hello',
b: 'hello2',
c: 'hello3'
};
var res = params.reduce((a, c) => {
return a += data[c] ? data[c] : c;
}, '')
console.log(res)