我有一个类似
的数组data['name']='Alex';
data['age']='21';
和类似
的字符串var text='My name is {name} and my age is {age}';
如何用相应的数组值替换括号之间的数据?
答案 0 :(得分:2)
您可以传递一个函数来替换
var text = 'My name is {name} and my age is {age}';
var data = {
name: 'foo',
age: 18
}
let res = text.replace(/\{(\w+)\}/g, (_, g) => data[g]);
console.log(res);
答案 1 :(得分:0)
您可以简单地遍历数组并获取名称和年龄。
var data = [{'name':'Alex','age':'18'}];
var text = '';
for(var i=0;i<data.length;i++){
text = "My name is "+ data[i].name+" and my age is "+ data[i].age+" .";
}
console.log(text);
答案 2 :(得分:0)
您可以使用模板字符串
在JavaScript中执行此操作// Template literals are enclosed by the back-tick (` `)
data['name']='Alex';
data['age']='21';
var text = `My name is ${data.name} and my age is ${data.age}`;
查看详细信息HERE
答案 3 :(得分:0)
var data = [];
data['name']='Alex';
data['age']='21';
var text='My name is {name} and my age is {age}';
var result = formatString(text, data); // desired output
console.log(result);
/* Replace the token values */
function formatString(text, data)
{
var keyNames = Object.keys(data);
for(var i = 0; i < keyNames.length ;i++)
{
text = text.replace("{"+ keyNames[i] +"}", data[ keyNames[i] ] );
}
return text;
}