Calculate mathematical expression in string

Asked

Viewed 2,404 times

4

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

How could I calculate?

2 answers

8


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;
  • Thank you, I forgot the function eval().

  • You’re welcome, you just need to call.

3

Use eval, changing format does not influence anything.

Example:

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

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

Just assign the value without Quotes.

  • To view this, visit the example http://jsfiddle.net/gt7gkcjp/

  • Eval is considered an unsafe and locked Method depending on where you use it. Ex.: Chrome Extensions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.