N15M0_jk N15M0_jk - 8 months ago 56
SQL Question

Javascript Boolean comparator from string

Unusual question here and maybe I'm approaching this issue incorrectly -

I'd like to do a comparison between some numeric values in Javascript, but I have the comparators stored in a database (in a VARCHAR field), where specific criteria are stored. (Comparators being <=, <, ==, >, >=, etc).

Is there a way to evaluate the string returned as a comparator in JS?


Answer Source

There is, but unless you're using it with completely trusted data, don't use it.

Instead, implement the comparisons:

function compare(operator, operand1, operand2) {
    switch (operator) {
        case "<=":
            return operand1 <= operand2;
        // ...and so on...

But yes, if you fully trust the data, you can use eval:

function compare(operator, operand1, operand2) {
    return eval("operand1 " + operator + " operand2");

(That looks like pseudo-code, but it isn't; eval evaluates the code string you give it in the context where you call it, so it has access to the operand1 and operand2 arguments.)

The "trust" part there is really, really important, because eval allows executing any script code.