1

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);
                    }
          });
2
  • Do they need to be right next to each other or just anywhere in the doc? Commented Oct 14, 2010 at 14:37
  • They can be anywhere in the attribute and separated by any words in any order. Commented Oct 14, 2010 at 15:23

3 Answers 3

1

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.)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.