RegExp / Jquery / Isotope Searching and filtering by keyword: not working with some keyword combination, why?

…衆ロ難τιáo~ 提交于 2021-01-05 09:04:52

问题


I am desperately trying to make the filtering work with multiple keywords. Somehow it doesnt work as expected. For example the keyword combination: laurene maria works but laurene maria ben or laurene ben or laurene clara and so on does not work. What have I dont wrong?

http://fiddle.jshell.net/7t8mgont/18/

var $quicksearch = $('#quicksearch').keyup( debounce( function() {
  qsRegex = new RegExp( $quicksearch.val(), 'gi' );
    $container.isotope({
        filter: function() {
            return qsRegex ? $(this).text().match( qsRegex ) : true;
          }
    });
}) );

Above is the essential section of the entire code. I also added a fully functional JSFiddle for you.

I would appreciate some insight.

Edit: I was thinking of str.split(" "); not sure though. My implementation didnt work


回答1:


Already one year old post and quite ugly javascript but if anybody search it, the idea is there ;)

I've take the idea from the combine filters (http://codepen.io/desandro/pen/mCdbD) but combining multiple regex. laurene maria AND maria laurene are working

jQuery('.quicksearch').keyup(function () {
    $grid.isotope({
        filter: function () {
            var qsRegex = [];
            var resultRegex = [];
            var endResult = new Boolean();
            var searchID = jQuery('.quicksearch').val();
            var searchTable = searchID.split(" ");
            for (var i = 0; i < searchTable.length; i++) {
                qsRegex[i] = new RegExp(searchTable[i], 'gi');
                resultRegex[i] = qsRegex[i] ? jQuery(this).text().match(qsRegex[i]) : true;
                endResult = endResult && resultRegex[i];
            }
            return endResult;
        }
    });
});



回答2:


Well, you have a few options.

Assuming that you only need to match words consecutively, e.g. laurene ben and not ben laurene, you can just pump simple regex into the string. You are exactly right with str.split(' '). So, to match any words that follow consecutively and allow for other words to come in between in the target string, use:

var regexVal = $quicksearch.val().split(/\s+/).join('\\b.*');
qsRegex = new RegExp(regexVal, 'gi');

I used .split(/\s+/) to match any number of consecutive spaces. The \\b makes sure that entire words are matched. If you would rather that the user be able to type any number of characters in any of the words, just take that out:

var regexVal = $quicksearch.val().split(/\s+/).join('.*');
qsRegex = new RegExp(regexVal, 'gi');

JSFiddle Here



来源:https://stackoverflow.com/questions/27756760/regexp-jquery-isotope-searching-and-filtering-by-keyword-not-working-with-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!