Search code examples
javascriptcalculatorprompt

Simple javascript prompt calculator


I am trying to make a simple calculator which calculates two numbers on js. It has 4 operations - "+","-","*" and "/". But the problem is that in current implementation it can operates only with one sign numbers))) What's the best way to solve this?

var express = prompt("Enter your operation, for example 2+2",""); 
if(!express) alert("Ok, it's over!");


express = express.replace(/\s/g, '');
var number1 = +express.charAt(0);
var sign = express.charAt(1);
var number2 = +express.charAt(2);

switch(sign){
case "+" : alert(number1 + number2);  break;
case "-" : alert(number1 - number2);  break;
case "*" : alert(number1 * number2);  break;
case "/" : alert(number1 / number2);  break;
 default : alert("Not a correct operation");
}

Solution

  • This works for integers. I think you can make it work for floats as well:

    var expression = "-30--20";
    
    match = expression.match(/^(-?\d+)([-+*/])(-?\d+)$/);
    
    if (match === null) {
        alert("invalid expression");
        return;
    }
    
    var number1 = match[1];
    var operand = match[2];
    var number2 = match[3];
    
    switch(operand){
        case "+" : alert(number1 + number2);  break;
        case "-" : alert(number1 - number2);  break;
        case "*" : alert(number1 * number2);  break;
        case "/" : alert(number1 / number2);  break;
        default : alert("Not a correct operation");
    }
    

    Gives -10.