I have an array like
data['name']='Alex';
data['age']='21';
and a string like
var text='My name is {name} and my age is {age}';
How to replace the data between brackets with corresponding array value ?
I have an array like
data['name']='Alex';
data['age']='21';
and a string like
var text='My name is {name} and my age is {age}';
How to replace the data between brackets with corresponding array value ?
You could pass a function to replace
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);
You can simply loop through your array and get the name and age.
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);
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;
}