Here’s an interesting one. Anyone have a good RegEx for converting all (first) ^ (second) to Math.pow((first), (second))?
EDIT:
The best I have so far is
s = s.replace(/((?:\d+\.?\d*)|\w+|\((?:(?:[^\(\)]*(?:\([^\(\)]*\)))*)\))\s*\^\s*((?:\d+\.?\d*)|\w+|\((?:(?:[^\(\)]*(?:\([^\(\)]*\)))*)\))/g, 'Math.pow($1, $2)') // replace expression ^ expression with Math.pow($1, $2)
The answers so far are not general enough. They don’t cover something like (var1 + var2)^2 let alone (var1 * (var2 + var3))^2
The solution will have to work with parentheses.
You can use strfriend.com to help visualize the regex as you make it. That’s what I’ve been doing.
This cannot be done with regex (at least not without lots of effort). You have to consider different layers of parenthesis, which can’t be handled with a simple regular expression. I suggest to look for a library capable of parsing mathematical expression. Or you’ll have to restrict the possible expression to something you can handle with a simple regex.
There is the possibility to define named and balancing capture groups in a regular expression which can be used (backreferenced) in the same regular expression. With this you would have to define the desired subset of the math syntax and both captures for the parameters. I suggest you should not reinvent the wheel and use a JS library.
http://snippets.dzone.com/posts/show/2207