javascript – Typeahead不敏感的口音

我试过this solution,但是我收到了这个错误:

Uncaught ReferenceError: normalized is not defined

这是我的代码:

var charMap = {
    "à": "a", "â": "a", "é": "e", "è": "e", "ê": "e", "ë": "e",
    "ï": "i", "î": "i", "ô": "o", "ö": "o", "û": "u", "ù": "u"
};

var normalize = function(str) {
      $.each(charMap, function(chars, normalized) {
        var regex = new RegExp('[' + chars + ']', 'gi');
        str = str.replace(regex, normalized);    
      });
      return normalized;
    }

var queryTokenizer = function(q) {
    var normalized = normalize(q);
    return Bloodhound.tokenizers.whitespace(normalized);
};

var spectacles = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: queryTokenizer,
    prefetch:'spectacles.json',
    limit:10,
  });
spectacles.initialize();

$('#search').typeahead({
  minLength: 1,
  hint:false,
  highlight: true
}, 
 {
  name: 'spectacles',
  displayKey: 'value',
  source: spectacles.ttAdapter()
}) ;

我的错误在哪里?谢谢

解决方法:

更改规范化函数,使其返回规范化的字符串,即

var normalize = function (input) {
 $.each(charMap, function (unnormalizedChar, normalizedChar) {
    var regex = new RegExp(unnormalizedChar, 'gi');
    input = input.replace(regex, normalizedChar);
 });
 return input;
}

看到我写的这个小提琴,看它工作:

http://jsfiddle.net/Fresh/SL36H/

您可以在浏览器调试控制台中看到规范化的字符串.在我的例子中,“àààèèèùùù”被转换为“aaaeeeuuu”.

请注意,我已经更改了函数参数,以便它们更准确(即字符不正确,它应该是char),并且我还合理化了正则表达式.

上一篇:javascript – 推特使用JSON对象预先输入Bloodhound


下一篇:腾讯提供的TBS调试小程序页面