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 can do this in JavaScript using template string
// 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}`;
check details HERE
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;
}
You could pass a function to replace