Sadikhasan
Sadikhasan

Reputation: 18600

How to check valid expression before evaluate?

My below code work perfect when valid maths expression but do not work when 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 to check valid mathematical expression before evaluate expression?

JS Fiddle

Upvotes: 3

Views: 1705

Answers (1)

dfsq
dfsq

Reputation: 193271

Wrap expression evaluation in the try/catch block and provide miningful message in case of 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);
}

Upvotes: 4

Related Questions