• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 401
  • Last Modified:

Regular Expression using Javascript to match all words in any order

Hi all,

I have a search string that I want to test against titles stored in another array.  for example
title = ["Handbook on Quality Assurance", "Water Quality Handbook", ...]
searchStr = "Handbook Quality"

I want to use regular expressions to test it each word is found at least once in the title but it doesn't matter in what order.  
I don't know how many words will be in the search string.
I've tried
new RegExp = ("("+searchStr.replace(" ", ")+.*(") + ")+");
(which would give /(Handbook)+.*(Quality)+/ in the above example)  
but this matches only title[0] and not title[1] (which I want to include).  

I was also thinking of using somewthing like /(Handbook|Quality) \1/  But if a title has the word Quality twice and not Handbook, it will still match (which I don't want)....

Because I have to loop through the title array (which is on the order of 200+ elements)  I don't want to have to do a sub loop for each of the search terms (which I don't how many there are) but can't think of any other way...

Any ideas???

Thanks,
Annie
0
andrea_lafleur
Asked:
andrea_lafleur
1 Solution
 
arataniCommented:
Regular expressions generally work from left to right, so you have to somehow specify the order the values come in.

The best way for you to do this (with my knowledge of regular expressions) is to use a simple loop search (and loop searching doesn't take too much time, it might actually be faster than using regular expressions). Cause eventually all regular expression searches use loops anyway.

I can help you write a loop, but i don't think it is possible to do what you want using regular expressions unless some other expert can teach me something more about regular expressions that i didn't know :)).

Take care

AJ

0
 
ZvonkoSystems architectCommented:
AJ is true, but to use any RegExp here my example:

<script>
title = ["Handbook on Quality Assurance", "Water Quality Handbook", "More Quality Handbooks", "Last Quality Handbook"];
searchStr = "Handbook Quality"
 aSearch = searchStr.split(" ");
 for(i=0;i<aSearch.length;i++){
   aSearch[i] = new RegExp("\\b"+aSearch[i]+"\\b", "i");
 }

 for(i=0;i<title.length;i++){
   found = true;
   for(j=0;j<aSearch.length;j++){
     found &= (title[i].match(aSearch[j])!=null)
   }
   if(found) alert(title[i]);
 }

</script>


0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now