Twitter typehead, фильтр Bloodhound начинается с

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

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(''))
    }
});

person Erhnam    schedule 17.11.2014    source источник


Ответы (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);
                };
            };
person Radenko Zec    schedule 15.06.2015