Reputation: 59
I have a JSON object that I use to send name: value form parameters, and some of the object values have references to another object between curly braces. I want to regex replace any such tags with the object value they reference.
I've tried using regular expressions to replace /\{([^}]+)\}/g
with obj['$1']
but it doesn't work.
var objArg = {
custom: [],
id: 188746,
name: "Miscellany",
format: "private",
section: "service",
material: ["internal"],
rack_plan_product_attributes: {
id: 531074,
product_attributes: {
id: 635366
}
},
make_up_policy_attributes: {
id: 324855
}
}
var s = 'The name is {name} and the rack plan product attributes id is {rack_plan_product_attributes.id}.';
s = s.replace(/\{([^}]+)\}/g, objArg['$1']);
Maybe I need to use a function like s = s.replace(/\{([^}]+)\}/g, function(r) { something... }
but I don't really understand how that works. I'm expecting the result to make s
into The name is Miscellany and the rack plan product attributes id is 531074.
Upvotes: 1
Views: 695
Reputation: 3291
You can eval the string as template literal if not supporting IE.
var s = 'The name is {objArg.name} and the rack plan product attributes id is {objArg.rack_plan_product_attributes.id}.';
s = eval( '`' + s.replace(/\s?{\s?/g, '${') + '`');
this part s.replace(/\s?{\s?/g, '${')
replaces {objArg.name}
with ${objArg.name}
eval()
will evaluate the string as javascript
Also be very careful with using eval
as it will execute the code it's passed with the privileges of the caller ... but honestly it hasn't been used to harm for a while now and if you are not using it on user input then you should be fine.
You can also wrap it in a function like:
function template(stringTemplate, {name, rack_plan_product_attributes}){
stringTemplate = eval( '`' + s.replace(/\s?{\s?/g, '${') + '`');
return s;
}
s = template( s, objArg )
or
If you have control over the string then you can just use the template literal explicitly by replacing your quotations with a tilde and adding dollar signs like so:
var s = `The name is ${objArg.name} and the rack plan product attributes id is ${objArg.rack_plan_product_attributes.id}.`;
Hope this helps
Upvotes: 1
Reputation: 842
You can use something like this:
var template = 'Hello {@name}'; //1
var data = {name: 'John'};
Object.keys(data).forEach(key => {//2
let strKey = '{@' + key + '}';
template = template.split(strKey).join(data[key]);//3 and 4
});
console.log(template);
Explanation: 1. have the template with a pattern that will be replaced ex: {@name} 2. iterate all the object so that it will try to find the key that matches the pattern, in this case data has key "name" and value "John" 3. split the string which now becomes ["Hello ", ""] 4. join the array with the value of name
Upvotes: 0