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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With