Twitter typeahead, Bloodhound filter startswith

1k Views Asked by At

I'm want to filter the results with a 'startswith' filter. Now the code below grabs everything that matches any of the separate words within the result. So when the user types "ex" both "example" and "one two example" are filtered out. How do I change this behavior so only "example" is filtered out?

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

There are 1 best solutions below

0
On

Just change substring function like this:

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