1

So I recently made a javascript calculator, and it works pretty well, except for when i start adding exponents.

Below will be a snippet the contains my calculator, and you can try for yourself something like 5^5+5^5, which equals 6250, but my calculator says 3135.

var isReset = 1;
function num(number){
  if(isReset == 1){document.getElementById("display").innerHTML = number.toString();isReset=0;}
else{
document.getElementById("display").innerHTML = document.getElementById("display").innerHTML + number.toString();}
}
function calculate(){
  document.getElementById("display").innerHTML = eval(document.getElementById("display").innerHTML.replace("^", "**").replace("x", "*").replace("÷", "/").replace("√", "Math.sqrt"));
isReset=1;
}
#container{
  position:absolute;
  left:40%;
  border:1px grey solid;
  top:40px;
}
<div id="container">
<div id="display">0</div>
<button onclick="num(1)">1</button>
<button onclick="num(2)">2</button>
<button onclick="num(3)">3</button>
<button onclick="document.getElementById('display').innerHTML = '0';isReset=1;">C</button>
<br>
<button onclick="num(4)">4</button>
<button onclick="num(5)">5</button>
<button onclick="num(6)">6</button>
<button onclick="num('&#247;')">&#247;</button>
<br>
<button onclick="num(7)">7</button>
<button onclick="num(8)">8</button
><button onclick="num(9)">9</button>
<button onclick="num('x')">x</button>
<br><button onclick="num('+')">+</button>
<button onclick="num(0)">0</button>
<button onclick="num('.')">.</button>
<button onclick="num('-')">-</button>
<br>
<button onclick="calculate()">=</button>
<button onclick="num('^')">^</button>
<button onclick="num('√&#40;')">√</button>
<button onclick="num('&#40;')">&#40;</button>
<br><button onclick="num('&#41;')">&#41;</button>
<button onclick="if(document.getElementById('display').innerHTML.length !== 1){document.getElementById('display').innerHTML = document.getElementById('display').innerHTML.substring(0, document.getElementById('display').innerHTML.length - 1);}else{document.getElementById('display').innerHTML = '0';isReset=1;}">Del</button>
</div>

This seems like its doing 5^5+5+5, and I don't know why.

Can anyone can tell me why this happens and what I can do to fix it?

mjm0813
  • 74
  • 6

1 Answers1

3

In JavaScript replace, when used with a string pattern, replaces only the first instance of that pattern. Yes, it’s really confusing.

console.log('bbbb'.replace('b', 'a'));

You have to use a regular expression with the g flag to replace all of them – and then you have to think about which characters have special meaning in regular expressions.

.replace(/\^/g, '**')

An alternative to String.prototype.replace with regular expressions is to split and then join:

.split('^').join('**')  // equivalent to .replaceAll('^', '**')
                        // if replaceAll existed

Without this, you’re getting (5**5 + 5) XOR 5.

Ry-
  • 218,210
  • 55
  • 464
  • 476