Reputation: 4366
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
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;
}
});
Upvotes: 0
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
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
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