How can I calculate the value of a mathematical function represented as a string?

For example: f(x,y) = 2*x + 5/y

How can you substitute x and y, then calculate the value of the function,

    2 answers 2

     var f = "f(x,y) = 2*x + 5/y"; var x = 100; var y = 2.5; f = f.replace(/f\(x,y\)\s=\s/g, ""); //удаляем лишнее f = f.replace(/x/g, x); // заменяем подстроку x на значение переменной x f = f.replace(/y/g, y); // тоже самое с y f = eval(f); // вычисляем значение строкового выражения console.log(f); 

    • And if the function has a degree, root, cosine, sine, etc.? I know that you can substitute Math.pow (), Math.sqrt (), etc. Is there any ready code for this? don't want to do your bike - Huffy Grams
    • There is a ready code, but you need to find it. This is already in Google. - Misha Saidov

    Found an excellent library for solving the problem "math.js":

     var f = "2*x^2 + sqrt(5/y)"; var fx = 2; var fy = 5 var node = math.parse(f); console.log(node.eval({x: fx, y: fy}));