I have a string like this:
"2 + 3 ^ 4"
That I want to be replaced with:
"2 + Math.pow(3, 4)"
So simply, I want the caret "^" sign to operate as the Math.pow function in my math expressions.
Then I could evaluate it:
eval("2 + Math.pow(3, 4)") -> 83
Here are a 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 I have tried:
String.prototype.replaceAt = function(index, character) {
return 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)")
for (var i = str.length - 1; i >= 0; i--) {
var m = str.lastIndexOf("^");
var c = 0;
for (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;
for (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 at all and very messy.