How do I check for a valid expression before evaluating?

My below code works fine when a valid expression is maths, but fails when the expression is invalid.

HTML code

<button id="calc">Calculate</button>
<p id="demo"></p>

      

JQuery code

function myFunction() {
    var x = 10;
    var y = 20;
    var a = eval("x * y") + "<br>";
    var b = eval("2 + 2") + "<br>";
    var c = eval("x + 17") + "<br>";
    var d = eval("x + 17 + ") + "<br>"; //here it is wrong expression throw error
    var res = a + b + c;
    $("#demo").html(res);
}

$("#calc").click(function(){
    myFunction();
});

      

My question is, how do I check for a correct math expression before evaluating the expression?

JS Fiddle

+3


source to share


1 answer


Wrap the evaluation of the expression in a try / catch block and get an error message on error:



function myFunction() {
    var x = 10;
    var y = 20;
    var res;

    try {
        var a = eval("x * y") + "<br>";
        var b = eval("2 + 2") + "<br>";
        var c = eval("x + 17") + "<br>";
        var d = eval("x + 17 + ") + "<br>";

        res = a + b + c;
    }
    catch (e) {
        res = 'Expression in invalid.';
    }

    $("#demo").html(res);
}

      

+4


source







All Articles