简体   繁体   中英

How do I replace variables with values inside a stringified function (Javascript)?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM