JavaScript Typeahead自动完成匹配重音和波浪号问题

我正在使用Typeahead jQuery库,但是当用户键入类似e人声时,它也应该匹配外国人声,例如éëè

nñ匹配。

这是我的代码:

          
var charMap = { "à": "a", "á": "a", "ä": "a", "è": "e", "é": "e", "ë": "e", "ì": "i", "í": "i", "ï": "i", "ò": "o", "ó": "o", "ö": "o", "ù": "u", "ú": "u", "ü": "u", "ñ": "n"}; var normalize = function (input) { $.each(charMap, function (unnormalizedChar, normalizedChar) { var regex = new RegExp(unnormalizedChar, 'gi'); input = input.replace(regex, normalizedChar); }); return input; } var substringMatcher = function(strs) { return function findMatches(q, cb) { var matches, substringRegex; matches = []; substrRegex = new RegExp(q, "i"); $.each(strs, function(i, str) { if (substrRegex.test(str)) { matches.push({ value: str }); } }); cb(matches); }; }; var nombres = ["Sánchez", "Árbol", "Müller", "Ératio", "Niño"]; $("#nombre .typeahead").typeahead({ hint: true, highlight: true, minLength: 1 }, { name: "nombres", displayKey: "value", source: substringMatcher(nombres) });

我怎样才能做到这一点?

谢谢!

我在下面的jsFiddle中写了一个解决方案:

http://jsfiddle.net/Fresh/F3hG9/

该解决方案的关键部分是规范化用于搜索的名称,并且还包括将用于显示目的的原始名称; 你可以在下面的“本地”定义中看到这个:

 var nombres = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: queryTokenizer, local: $.map(names, function (name) { // Normalize the name - use this for searching var normalized = normalize(name); return { value: normalized, // Include the original name - use this for display purposes displayValue: name }; }) }); 

Normailze函数(如下所示)用西方替代品取代“外国”字符:

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

为简洁起见,我省略了charMap(它决定了外来人物映射到的西方字符); 你可以找到小提琴中的列表。