Say I have a variable str
var str = "123"
Now I could do console.log(`Hello ${str}`)
and it will print Hello 123
Now I have another variable strnew
var strnew = 'Hello ${str}'
Note (based on answers/comments) - strnew
is read from a file, so its always a string and cant be replaced with `
How do I console.log(...)
to print Hello 123
Is it possible wihtout any kind of eval()
String interpolation is common in many programming languages which make heavy use of string representations of data, such as Apache Groovy, Julia, Kotlin, Perl, PHP, Python, Ruby, Scala, Swift, Tcl and most Unix shells.
String interpolation is a process substituting values of variables into placeholders in a string. For instance, if you have a template for saying hello to a person like "Hello {Name of person}, nice to meet you!", you would like to replace the placeholder for name of person with an actual name.
Interpolation: The variable parsing is allowed when the string literal is enclosed with double quotes or with heredocs. Single quoted string or nowdocs, does not supports variable interpolation.
With something as simple as ${str}
you can use a simple string replacement:
var template = (tpl, args) => tpl.replace(/\${(\w+)}/g, (_, v) => args[v]); var tpl = 'Hello ${str} and ${other}'; console.log(template(tpl, {str: 'foo', other: 'bar'}));
In a general case, no, not possible without eval (short of writing your own js interpreter), because ${...}
can contain arbitrary expressions.
For completeness' sake, here's the eval solution:
var template = function(tpl, args) { var keys = Object.keys(args), fn = new Function(...keys, 'return `' + tpl.replace(/`/g, '\\`') + '`'); return fn(...keys.map(x => args[x])); }; function test() { var myTpl = 'Hello ${str + "!"} and ${other.toUpperCase()}'; console.log(template(myTpl, {str: 'foo', other: 'bar'})); } test();
You can use function instead of just string.
var strnew = function(str){ return `Hello ${str}`; } var str = "123"; console.log(strnew(str))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With