How to find if the previous character is the same

Viewed 58

I am trying to create a calculator.

My problem is the buttons could be double clicked creating 2 of the same characters next to each other (Example: 2++2). I want to remove the second plus sign.

So far I've managed to use this:

if(!y.includes("+")) {
  summed.push("+")
  document.getElementById("num").innerHTML = summed.join('')
}

But this will only allow 1 plus sign and would disable any other. My intended solution should be this (3+3+3) and not this (3++3). Hopefully this is understandable.

2 Answers

Simply check last character y[y.length - 1] is not +.

if(y && y.length >0  && y[y.length - 1] !== "+") {
  summed.push("+")
  document.getElementById("num").innerHTML = summed.join('')
}

try out this:

let math = [...]

if(math[math.length - 1] == "+") {
// do not allow to append another +
}
Related