Filter Table Data where ALL words of a query are matched
I was implementing the filtering code on the tutorial found below: http://net.tutsplus.com/tutorials/javascript-ajax/using-jquery-to-manipulate-and-filter-data/
What this basically does is find out rows which have words of your query and show only those rows. The thing is that it uses OR between words of the query. So if my query is 'hello world' it will show me rows that have 'hello' OR 'world' in them.
What i would like to do is use AND instead of OR so that rows having 'hello' AND 'world' show up. The code is below:
function filte开发者_如何学Gor(selector, query) {
query = $.trim(query); //trim white space
query = query.replace(/ /gi, '|'); //add OR for regex query
$(selector).each(function() {
($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide().removeClass('visible') : $(this).show().addClass('visible');
});
}
Thank you for helping me out
As you have seen, implementing OR logic within a regex is pretty straightforward. Doing AND logic is a bit more envolved. To accomplish this, you can apply multiple positive lookahead assertions from a position at the beginning of the string. To illustrate how this can be done, here is a commented regex written in PHP...
if (preg_match(
'/# Match a string containing "word1" AND "word2" AND "word3".
^ # Anchor to start of string
(?=.*?\bword1\b) # Ensure there is a "word1" in string
(?=.*?\bword2\b) # AND ensure there is a "word2" in string
(?=.*?\bword3\b) # AND ensure there is a "word3" in string
/ix', $contents)) {
# Successful match. All the words are in the $contents string.
} else {
# Match attempt failed.
}
Next all you need to do is assemble a similar regex using Javascript. Here is an AND filter function:
function filter_AND(selector, query) {
query = query.split(/\s+/); // Array of words to be matched.
var len = query.length; // Save length for speed in loop.
var re_word = /^\w(?:.*\w)?$/; // Regex to validate a single word.
var regex = '^'; // Begin assempling our "AND" regex.
for (var i = 0; i < len; ++i) { // Loop adding each word to regex.
if (re_word.test(query[i])) { // If it begins and ends with '\w',
regex += '(?=.*?\\b' + query[i] + '\\b)'; // add word to regex.
}
}
regex = new RegExp(regex, 'i'); // Convert string to Regex object.
$(selector).each(function() {
($(this).text().search(regex) < 0) ?
$(this).hide().removeClass('visible') :
$(this).show().addClass('visible');
});
}
Hope this helps! 8^)
精彩评论