0

I'm building a vanilla JS calculator and trying to use a regex .test() function to restrict the user from using an operator more than once in a row

i.e. 2++++3

It is structured as an if else statement, and the problem is that the regex test works on the first time, but then fails the second time thus causing the code to jump to the else statement when it shouldn't. Is my regex wrong? Am I using the wrong function to run the comparison?

var testOperands = /[+-/*=]/g;
switch (x) {

  case "+":
    if(testOperands.test(currentEntry[0])){
      currentArea.textcontent = x;
      totalArea.textContent = totalArea.textContent + "";
    } else {
    currentArea.textContent = x;
    totalArea.textContent = (totalArea.textContent + x);
    currentEntry = ["+"];
    totalEntry.push(x);
    }
    break;
  case "-":
    if(currentEntry[0] === "-"){
      currentArea.textcontent = x;
    } else {
    currentArea.textContent = x;
    totalArea.textContent = (totalArea.textContent + x);
    currentEntry = ["-"];
    totalEntry.push(x);
    }
    break;

here is the full code: https://codepen.io/brianofblades/pen/KQWVYN

jolt
  • 21
  • 6
  • Possible duplicate? -> https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results – Jankapunkt Feb 09 '18 at 14:55

3 Answers3

3

Your regex is invalid, - needs to be escaped: [+\-\/*=]

Richard
  • 951
  • 7
  • 14
0

/^[+\-%*]?$/g

Feel free to add more symbols into the square brackets but this Regex checks for 0 or 1 of any of those character...any more than 1 and the test will not pass...

let reg = /^[+\-%*]?$/g

console.log(reg.test('+')) //true
console.log(reg.test('++')) //false

Use this regex to check for multiple operators IN-BETWEEN numbers or any length.

let reg = /^([0-9]+[+\-%*]?[0-9]+)$/g

console.log(reg.test('123+123')) //true
console.log(reg.test('123++123')) //false
Francis Leigh
  • 1,870
  • 10
  • 25
0

Regex: [-+\/*=]{2,}

function myFunction() {
  console.clear()
  var s = document.getElementById("input").value;
  console.log(/[-+\/*=]{2,}/.test(s));
}
<form action="javascript:myFunction()">
  <input id="input" type="text" name="math" value="2++3"><br><br>
  <input type="submit" value="Submit">
</form>
Srdjan M.
  • 3,310
  • 3
  • 13
  • 34