views:

33

answers:

3

I'm trying to create a Regex with jQuery so it will search for two words in an attribute of an XML file.

Can someone tell me how to return a result that contains BOTH words (sport and favorite) in any order and any case (upper or lower case)?

var regex = new RegExp("sport favorite", 'i');

var $result = $(data).filter(function() {
                    if($(this).attr('Description')) {
                        return $(this).attr('Description').match(regex);
                    }
          });
+1  A: 
var regex = new RegExp("sport favorite|favorite sport", 'i'); 
Michael Goldshteyn
A: 

If they may be separated by any character, you could do it like this:

var regex = new RegExp(".*sport.+favorite.*|.*favorite.+sport.*", 'i'); 

(This assumes that no other word in the attribute contains the substring favorite or sport.)

steinar
Thanks guys. That works great!
jttm
A: 

The "\b" marker can be used to "match" the edges of words, so

var regex = /\bsport\b.*\bfavorite\b|\bfavorite\b.*\bsport\b/i;

matches the words only as words, and (for example) won't match "sporting his favorite hat".

Pointy