The easiest way is to pass a function instead of a string:
var strf = name => `Hi, ${name}!`; func("Mark", strf); function func(name, strf) { console.log(strf(name)); }
In more complex cases, you will need new Function (but make sure that untrusted strings do not get there!):
var str = 'Hi, ${name}!'; var strf = compile(str); func("Mark", strf); function func(name, strf) { console.log(strf(name)); } function compile(str) { return new Function("name", "return `" + str + "`"); }
Even if the names of the variables are unknown in advance, you will have to use the obsolete construction with :
var str = 'Hi, ${name}!'; var strf = compile(str); func({ name: "Mark" }, strf); function func(data, strf) { console.log(strf(data)); } function compile(str) { return new Function("$data", "with ($data) return `" + str + "`"); }
But it is better not to bring it up to this and dwell on the first variant.
`(where the letter is e), not'........var str = `hi ${name}`;....... although in your case you are trying to do something completely strange - Alexey Shimansky