0

Я хочу отфильтровать результаты с помощью фильтра «startswith». Теперь приведенный ниже код захватывает все, что соответствует любому из отдельных слов в результате. Поэтому, когда пользователь набирает «ex», отфильтровываются как «пример», так и «один два примера». Как изменить это поведение, так что только «пример» отфильтровывается?Twitter typeahead, фильтр Бладхаунда startswith

var repos; 

repos = new Bloodhound({ 
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), 
queryTokenizer: Bloodhound.tokenizers.whitespace, 
limit: 10, 
    prefetch: { 
     name: 'terms', 
     url: 'search.php', 
    } 
}); 

repos.initialize(); 

$('input.typeahead').typeahead(null, { 
    name: 'repos', 
    source: repos.ttAdapter(), 
    templates: { 
     empty: '<div class="empty-message">No matches.</div>', 
     suggestion: Handlebars.compile([ 
      '<div class="term-box" id="{{id}}">', 
      '<p class="term">{{termname}}</p>', 
      '</div>' 
     ].join('')) 
    } 
}); 

ответ

1

Просто измените функцию подстроки, как это:

var substringMatcher = function (strs) { 
       return function findMatches(q, cb) { // an array that will be populated with substring matches 
        var matches = []; 

        // regex used to determine if a string contains the substring `q` 
        //var substrRegex = new RegExp(q, 'i'); 

        // we use starts with instead of substring 
        var substrRegex = new RegExp('^' + q, 'i'); 


        // iterate through the pool of strings and for any string that 
        // contains the substring `q`, add it to the `matches` array 
        $.each(strs, function (i, str) { 
         if (substrRegex.test(str)) { 
          matches.push(str); 
         } 
        }); 

        cb(matches); 
       }; 
      }; 
Смежные вопросы