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

JavaScript Typeahead Autocomplete match accents and tildes Issue

本文关键字:问题 Typeahead JavaScript      更新时间:2023-09-26

我使用的是Typeahead jQuery库,但是当用户键入像e这样的人声时,它也应该匹配外语人声,如éëè

n也匹配ñ

这是我的代码:

<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="typeahead.css">
    <script src="jquery-1.11.0.min.js"></script>
    <script src="typeahead.bundle.min.js"></script>
</head>
<body>
    <center>
        <div id="nombre">
            <input class="typeahead" type="text" placeholder="Nombre">
        </div>
    </center>
    <script>
        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)
        });
    </script>
</body>

我怎样才能做到这一点?

谢谢!

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

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

该解决方案的关键部分是规范化用于搜索的名称,并包括将用于显示目的的原始名称;您可以在下面的"local"定义中看到这一点:

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(它决定了外国字符映射到哪个西方字符);你可以在小提琴中找到列表。