Calculate mathematical expression in string

4

Hello, I would like to know how I can compute a math expression, contained in a string, in Javascript. Example: calc = "(7*2+1)/2";

How could I calculate?

    
asked by anonymous 15.07.2015 / 00:34

2 answers

7

Using the eval method.

calc = eval("7*2+1/2");

Another example:

var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";

var res = a + b + c;
    
15.07.2015 / 00:38
3

Using eval , changing format does not influence anything.

Example:

var Variavel = 7*2+1/2; alert(Variavel);

Returns the same value as alert(eval("7*2+1/2"));

Only the value without quotes.

    
15.07.2015 / 13:24