Home > database >  Changing javascript eval method to another solution
Changing javascript eval method to another solution

Time:01-02

I try to get rid of an ugly javscript eval method (Cause we all know it is unsecure). I have the following problem. I build a dynamic searchstring. Depends on the TLD a user decided to search for.

Here is my code:

 if (tld == 0) {
            var searchString = 'value.tld != ""';
        }
        if (tld == 1) {
            var searchString = 'value.tld == "de"';
        }
        if (tld == 2) {
            var searchString = 'value.tld == "com" || value.tld == "net" || value.tld == "org" || value.tld == "info" || value.tld == "biz"';
        }
        if (tld == 3) {
            var searchString = 'value.tld == "io"';
        }

Depending on the search parameter 'searchstring', I build this routine with eval:

if (eval(searchString)) {
    // Do something special, depends on the tld variable
}

How can i rebuild this without using 'eval'. The premission is, that the first part of the code is beeing untouched.

Thanks in advance

Nick

CodePudding user response:

How about:

let choices = {
  1: ['de'],
  2: ['com', 'net', 'org', 'info', 'biz'],
  3: ['io']
};

function check(tldparam) {
  if (tld === 0) {
     return value.tld !== "";
  } else {
    return tld === tldparam && choices[tldparam].includes(value.tld);
  }
}

And we test it like:

// Got this value from somewhere
let tld = 2;
let value = {tld: 'net'};

// This is my checking criterion
let tldparam = 2;

if (check(tldparam)) {
    // Do something special, depends on the tld variable
}

Does it serve your purpose?

  • Related