Reputation: 1543
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.
Upvotes: 0
Views: 2501
Reputation: 1264
You could use a recursive function that stops when no other token was matched. For example:
var str = '2^2^2';
var regex = /(\d+)\^(\d+)/g;
function recursive(str) {
var matched = false;
str = str.replace(regex, function(match, $1, $2) {
if (match) {
matched = true;
}
return Math.pow($1, $2);
});
if (matched) {
str = recursive(str);
}
return str;
}
var result = recursive(str);
console.log(result);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Upvotes: 2