Reputation:
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 ?
Upvotes: 0
Views: 454
Reputation: 1
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;
}
Upvotes: 0
Reputation: 2643
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
Upvotes: 0
Reputation: 3305
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);
Upvotes: 0
Reputation: 73231
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);
Upvotes: 1