1

Consider the following :

var a = 5;

var b = function ()
{
  console.log (a + 5);
};

var c = b.toString();

after the above has been executed, c will be equal to :

"function ()
 {
   console.log (a + 5);
 }"

How can I have c be equal to :

"function ()
 {
   console.log (5 + 5);
 }"

instead?

I tried the following :

var a = 5;

var b = function ()
{
  console.log ('<%a%>' + 5);
};

var c = b.toString().replace('<%a%>', a);

But the above obviously makes c equal to :

"function ()
 {
   console.log ('5' + 5);
 }"

Is there some other way of achieving this (javascript + RegEx) without using libraries like underscore (with the known template function) ?

Basically I'm trying to come up with a neat function that will convert a function into a string while at the same time replacing all variables (that have a hardcoded value) present in that function with their respective values, without the use of any variables.

Thanks

1 Answer 1

5

You can fix your snippet by changing the first argument of .replace:

var a = 5;

var b = function ()
{
  console.log ('<%a%>' + 5);
};

var c = b.toString().replace("'<%a%>'", a);

For more generic solution you may need smarter parser with syntactical analysis.

Sign up to request clarification or add additional context in comments.

1 Comment

Damn it. So simple. How did I miss that? And you're right my approach is very simplistic and I'm pretty sure it will break with more elaborate types of variables. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.