-1

I have the situation that I retrieve a function in a string:

var function_name = "function Test(value){return value + 1}";

now I want to execute the function and store the value inside a variable so for example:

var value = 10;
var calc_value = function Test(value){return value + 1}
console.log(calc_value); // should show 11

But I do not know how I could get the function out of the string and execute it and store the result in a variable.

Any ideas how I could do that? I know that having the function inside a string is not ideal at all but I can not change that.

Rotan075
  • 2,567
  • 5
  • 32
  • 54

2 Answers2

3

You can use eval(). For eg:

var str='function Test(value){return value + 1}';
    eval(str);
    alert(Test(3));
Tejasvi Karne
  • 628
  • 4
  • 14
0

You can use eval() to evaluate the expression

var str="function Test(value){return value + 1}";
eval(str);
console.log(Test(1));
marvel308
  • 10,288
  • 1
  • 21
  • 32