I have a mathematical expression that does exponentials (e.g. 2 Raised to the power of 2) which I normally pass to the JavaScript eval function. An example of my string expression is 2^2^2. Now, JavaScript doesn't have an exponential operator so in the current example the operator you see between the operands is a bitwise operator in JavaScript.
What I try to do is to replace the string that matches the pattern d1 ^ d2 with the value returned from Math.pow (d1, d2). Now, it does this successfully for the first occurence but doesn't do it for other occurrences. Below is my code:
var str = '2^2^2';
var regex = /(\d+)\^(\d+)/g;
str = str.replace(c, function(match, $1, $2) {
console.log(match + '---' + $1 + '---' + $2);
return Math.pow($1,$2);
});
console.log(str);
eval(str);
Anytime I log the ouput of str it gives 4^2 instead of 16 and so I always get the wrong answer after the eval function actions. Please does anyone have any idea how I can go about solving this problem.