My app fetch a list of resources strings + placeholders tokens and it should change the token with a given value.
An example of such resource is : "http://example.com/?name=${name}&age=${age}";
(I get many like these in an array but that's not relevant).
So now I have this^ string and I have the values. So I need to generate the digested string.
Sure I can use eval :
var template = "http://example.com/?name=${name}&age=${age}";
var name = "John";
var age = "30";
var url = eval(`\`${template}\``);
console.log(url); //http://example.com/?name=John&age=30
This works.But I don't want to use eval.
So I've switched to other approach of new Function()() :
var url = new Function ('tmpl','obj','return `${tmpl}`')
This yields the function:
ƒ anonymous(tmpl,obj ) {
return `${tmpl}`
}
So now I can do :
new Function ('tmpl','obj','return `${tmpl}`')(template ,{name, age})
But now I need to break apart obj within the inner function so that the template literal will know the values
BTW - I've tried this - with no success:
(new Function ('tmpl','obj','return `${tmpl}`').bind({name,age})) (template)
Question
How can I flatten obj in the inner function so that ${} will have known local values?
Nb I prefer not to go to regex solutions becuase of line breaks pros in template literals. and besides , those resources are intentionally in a format of es6 template strings
${tmpl}"tmplas a string.