如何用bloodhound / typeahead忽略标点符号和符号

时间:2015-04-13 03:48:10

标签: javascript typeahead.js

我已经打了一个带有猎犬的打字机从学校名单中拉出来,但是它会与像这样的案件混在一起。

A.B. Meadows

当有人输入时:

AB

文档说Bloodhound有一个tokenizer功能,显示的例子让我相信它能够处理这个问题。有任何想法吗?完整代码发布在下面。

var schools = ['A.B. Meadows','F.D. Creekfield'];
// constructs the suggestion engine
  var schoolSuggest = new Bloodhound({
    limit: 10,
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: $.map(schools, function(school) { return { value: school }; })
  });

  // kicks off the loading/processing of `local` and `prefetch`
  schoolSuggest.initialize();

  $('.schoolward').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
  },
  {
    name: 'wards',
    displayKey: 'value',
    source: schoolSuggest.ttAdapter()
  });

1 个答案:

答案 0 :(得分:0)

如果所有数据都是本地数据,那么像str.replace(/\./g,'');这样的正则表达式的子字符串匹配器应该会有所帮助。下面是子串匹配器。

var substringMatcher = function (strs) {
    return function findMatches(q, cb) {
        var matches, substrRegex;
        matches = [];
        substrRegex = new RegExp(q, 'i');
        $.each(strs, function (i, str) {
            str2 = str.replace(/\./g,''); // this will remove period from being considered in search
            if (substrRegex.test(str2)) {
                matches.push({
                    value: str
                });
            }
        });
        cb(matches);
    };
};

这是 DEMO