Derek
Derek

Reputation: 2112

Javascript logical search?

I've built a search function for an array of javascript objects along the lines of:

  1. User types text into a form input box
  2. Loop through object array
  3. If object text contains inputted text, push the object into a separate 'filtered' array
  4. Display filtered array

This works fine using the string search() function built into javascript ie.

if(objectarray[i].text.search(userstring)>=0){  
    filteredarray.push(currentobject)  
};

Now the client would like to do a more advance search along the lines of:

find objects where text contains (x1 or x2) and (x3 or x4 or x5)

Where each of the x's is a word and an object would be pushed into the filtered collection when the above condition is met.

Is there a built in function which can handle this kind of complex boolean statement?

Upvotes: 2

Views: 2567

Answers (1)

Derek
Derek

Reputation: 2112

Using the answer to this question

I take this:

var usersearchstring = "(x1 or x2) and (x3 or x4 or x5)";

And convert it using this:

usersearchstring = usersearchstring.replace(/[-\w]+/g, "targetstring.toLowerCase().search('$&')>=0");

Into this:

(targetstring.toLowerCase().search('x1')>=0 or targetstring.toLowerCase().search('x2')>=0) and (targetstring.toLowerCase().search('x3')>=0 or targetstring.toLowerCase().search('x4')>=0 or targetstring.toLowerCase().search('x5')>=0)

N.B. '>=0' is required to convert the numerical response returned by the search function into a boolean value

Upvotes: 2

Related Questions