4

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,698
  • 14
  • 54
  • 103

2 Answers2

16

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
  • 557
  • 4
  • 11
15
var x = a number;
var n = eval("2*Math.pow(x,3)+3*x+6")
Shmiddty
  • 13,669
  • 1
  • 33
  • 52