Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert equation string to equation [duplicate]

Tags:

javascript

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?

like image 578
Max Hudson Avatar asked Nov 27 '22 07:11

Max Hudson


1 Answers

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.

like image 107
tjdecke Avatar answered Dec 09 '22 19:12

tjdecke