I’m at the moment trying to plot formulas on HTML5 <canvas> by letting the user put in a formula. This works great through eval(); however, the ^ means bitwise XOR in Javascript, while it should mean ‘to the power of’ in a formula.
So basically I’d have to rewrite something like x^4 to Math.pow(x, 4). I came up with using regular expressions. This one however only works to a certain extent:
"x^4".replace(/(.*)\^(.*)/g, "Math.pow($1, $2)")
It does rewrite x^4 to Math.pow(x, 4), but for more advanced formulas this goes wrong. For example, 2 + x^4 is rewritten as Math.pow(2 + x, 4), while it should of course be 2 + Math.pow(x, 4). Moreover, if the exponent has brackets around it, e.g. 2^(x+1) + 3, it should be rewritten to Math.pow(2, x+1) + 3 instead of Math.pow(2, x+1 + 3), of course.
How would I go about rewriting this so that only the correct parts are put into the pow function? I really do not see where to start, so any tips would be greatly appreciated.
This is a tricky one. What you’re talking about here is an expression parser.
You might want to take a look at Jison, which is designed to help people solve this type of problem.
Regular expressions aren’t really the best way to do parsing of tokenized strings. One of Jison’s demos is precisely what you’re looking for, in terms of expression parsing, leaving you to work on the fun stuff of function graphing.