jquery - Javascript dynamic IF regex condition without eval? -
i'm adding multi-group checkbox filtering (multiple unordered lists of checkboxes) web app , i'm stuck trying around using eval (or maybe shouldn't worry in case?). basically, data called 1 ajax call, i'm storing in array of objects , i'm doing live filtering without making additional ajax calls. when checkboxes checked i'm using .match() , i'm creating regular expression string values in array (k category object property, such category1):
filterargs.push("(data['" + k + "'].join(', ').match(/" + filters[k].join('') + ".+/))");
the filters array set in loop above , looks (v actual string value - category name):
filters[k][z] = '(?=.*\\b' + v[z] + '\\b)';
then i'm joining filterargs:
return filterargs.join(' && ');
filterargs passed if statement condition eval this:
if(eval(filter_setup())){
so, if if statement true, correct object main data array included in filtered set of data. i'm going switch jquery's $.grep instead of if statement still run same eval issue. there other way build dynamic regular expression? it's working fine eval i've read articles saying how "evil" is. if statement condition ends looking following (2 boxes checked in first group , 1 in group):
(data['type'].join(', ').match(/(?=.*\brestaurant\b)(?=.*\bbar\b).+/)) && (data['state'].join(', ').match(/(?=.*\bwashington\b).+/))
avoid eval
as possible. in case, it's not necessary.
store filter
object when needed , define this:
function checkfilters(data, filters) { (var k in filters) { if (!(new regexp(filters[k].join("")).test(data[k]))) return false; return true; }
so can use this:
if (checkfilters(data, filters)) { ... }
by way, creating regexp
object using constructor expensive. if need more speed, can precompile filters , keep them instead of array of conditions:
filters[k] = new regexp(filters[k].join(""));
additionally, dave noted, depending on data may need escape filters:
filters[k][z] = '(?=.*\\b' + v[z].replace(/([\^\$\/\.\*\+\?\|\(\)\[\]\{\}\\])/g, "\\$1") + '\\b)';
Comments
Post a Comment