Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  140] [ 5]  / answers: 1 / hits: 22701  / 12 Years ago, thu, january 10, 2013, 12:00:00

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?


More From » javascript

 Answers
10

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.


[#80958] Wednesday, January 9, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alorafrancisl

Total Points: 80
Total Questions: 96
Total Answers: 102

Location: Ukraine
Member since Sun, Dec 13, 2020
4 Years ago
;