HGPB
HGPB

Reputation: 4366

Need a specific Javascript match regex

I currently have the following:

var sText = 'I like stackoverflow';

if ( $(this).text().match( eval("/" + sText + "/ig") ) ) {

As you can see, this matches the entire string.

I need to match case insensitive text that contains all the words individually. So it will look for "I", "like" and "stackoverflow". It must have all 3 words.

Much appreciate the help.

Upvotes: 0

Views: 534

Answers (4)

Chris Marasti-Georg
Chris Marasti-Georg

Reputation: 34650

I think this is what you're looking for - the key is the word boundaries.

    var text = "text to match"

    var stringToLookFor = "I like stackoverflow";
    var words = stringToLookFor.split(" ");
    var match=true;
    $.each(words, function(index, word) {
        if(!text.match(eval("/\\b" + word + "\\b/i"))) {
            match=false;
            return false;
        }
    });

JSFiddle example.

Upvotes: 0

Pi Delport
Pi Delport

Reputation: 10598

If you really need to do this with a match, you can use multiple positive lookahead patterns. For example, to match a, b, and c, in any order:

> p = /(?=.*a)(?=.*b)(?=.*c)/i

> 'abc'.match(p)
[""]

> 'cba'.match(p)
[""]

> 'ac'.match(p)
null

Upvotes: 1

ipr101
ipr101

Reputation: 24236

You could just split then loop -

var sText = 'I like stackoverflow';
var cText = 'stackoverflow like I';
var arr = sText.split(' ');
var match = true;

for (i=0;i<arr.length;i++) {
  if (!cText.match(eval("/" + arr[i] + "/ig"))) match= false;
}

alert(match);

You'd need to keep efficiency in mind if you were comparing lots of words though.

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

Why use regular expressions when .indexOf will do the job?

var str = $(this).text().toLowerCase();
if (str.indexOf('i')>=0 && str.indexOf('like')>=0 && str.indexOf('stackoverflow')>=0) {  
    // ...
}

(Mind you, in this case the "i" search is wasted since it's contained in "like", but I assume your actual code is searching for more ordinary text.)

Possible related question: JavaScript: case-insensitive search

Upvotes: 0

Related Questions