0

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.

Tushar
  • 85,780
  • 21
  • 159
  • 179
user3775998
  • 1,393
  • 3
  • 13
  • 22

1 Answers1

2

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>
Tushar
  • 85,780
  • 21
  • 159
  • 179
Lulylulu
  • 1,254
  • 8
  • 17
  • @Tushar do u have any idea how i can write the regex such that the replace works for negative, positive and decimal numbers? Thanks – user3775998 Apr 15 '16 at 09:57