6

Possible Duplicate:
Running an equation with Javascript from a text field

How can I convert the following:

var n = "2x^3+3x+6";

To

var x = a number
var n = 2x^3+3x+6;

In JavaScript?

Community
  • 1
  • 1
Max Hudson
  • 9,961
  • 14
  • 57
  • 107

2 Answers2

17
var x = a number;
var n = eval("2*Math.pow(x,3)+3*x+6")
Shmiddty
  • 13,847
  • 1
  • 35
  • 52
17

Quite hard to guess what the exact requirements and the context are, but if you want to roughly stick to the grammar demonstrated by your variable I'd suggest using a math expression parser.

Using js-Expression-eval, it could look like this:

var formula = "2*x^3+3*x+6";
var expression = Parser.parse(formula);
var result = expression.evaluate({ x: 3 });

Run the Fiddle

Should you want to have your own grammar - to leave out the * symbols for multiplication with variables, for example - you'll have to roll your own parser, for example using something like jison.

tjdecke
  • 567
  • 4
  • 11