Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation on variable

Tags:

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()

like image 661
Faiz Mohamed Haneef Avatar asked Dec 13 '16 09:12

Faiz Mohamed Haneef


People also ask

Which strings do interpolate variables?

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.

How is string interpolation performed?

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.

Which strings do not interpolate variables?

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.


2 Answers

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();
like image 79
georg Avatar answered Sep 18 '22 12:09

georg


You can use function instead of just string.

var strnew = function(str){    return `Hello ${str}`;  }  var str = "123";  console.log(strnew(str))
like image 20
Dmitry Masley Avatar answered Sep 21 '22 12:09

Dmitry Masley