regex - Javascript - Custom math expression parsing -
i have string this:
"2 + 3 ^ 4"
that want replaced with:
"2 + math.pow(3, 4)"
so simply, want caret "^" sign operate math.pow function in math expressions.
then evaluate it:
eval("2 + math.pow(3, 4)") -> 83
here few more examples:
"4 ^ 3 ^ 2" -> "math.pow(4, math.pow(3, 2))" "4 ^ (3 ^ 2) ^ 2 ^ 1" -> "math.pow(4, math.pow(math.pow(3, 2), math.pow(2, 1)))" "4. ^ math.sqrt(2) ^ 3" -> "math.pow(4., math.pow(math.sqrt(2), 3))" "2 ^ 3e-2" -> "math.pow(2, 3e-2)" "-5 ^ .2" -> "-math.pow(5, .2)" "(-5) ^ 2" -> "math.pow(-5, 2)" ".2 ^ -infinity" -> "math.pow(.2, -infinity)" "2.34 ^ ((3 + 2) * math.sin(3))" -> "math.pow(2.34, (3 + 2) * math.sin(3))" "math.cos(2) ^ (3 + 2)" -> "math.pow(math.cos(2), 3 + 2)"
what have tried:
string.prototype.replaceat = function(index, character) { homecoming this.substr(0, index) + character + this.substr(index+character.length); } str = str.replace(/ /g, ""); str = str.replace(/((?:(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?|infinity))/g, "($1)") (var = str.length - 1; >= 0; i--) { var m = str.lastindexof("^"); var c = 0; (var j = m + 1; j < str.length; j++) { if (str[j] == "(") c++; if (str[j] == ")") c--; if (c == 0) { str = str.replaceat(j + 1, str[j + 1] + ")") break } } c = 0; (var j = m - 1; j >= 0; j--) { if (str[j] == "(") c++; if (str[j] == ")") c--; if (c == 0) { str = str.replaceat(j - 1, "math.pow(" + str[j - 1]) break } } str = str.replaceat(m, ",") }
doesn't work @ , messy.
use http://mathjs.org/
it allows calculate expressions
print(math.eval('sqrt(3^2 + 4^2)'));
using stacks can create class can convert mathematical look js understandable expression, possibility of achieving test cases correctly requires lot of testing. improve utilize libraries (they have docs , illustration available online).
javascript regex string syntax
No comments:
Post a Comment