在List.js中使用非英语字符

时间:2015-04-02 16:10:53

标签: javascript regex special-characters listjs

我有一个使用List.js库创建的功能列表。有什么方法可以将非英语字符与常规字符匹配吗? 例如,列表包含以下元素:'şuncă','brânză','mărar'。 我很好奇是否有办法找到这些元素,即使我在没有非英文字符的情况下搜索,例如:'sunca','branza','marar'

1 个答案:

答案 0 :(得分:0)

使用filter() API function和帮助函数将字符串中的重音字符替换为其基本版本。

助手功能

// generic accent removal from input string, add any missing characters
var removeAccents = (function () {
    var letters1 = "äáàâăëéèêĕüúùûŭöóòôŏÄÁÀÂĂËÉÈÊĔÜÚÙÛŬÖÓÒÔŎßșȘ",
        letters2 = "aaaaaeeeeeuuuuuoooooAAAAAEEEEEUUUUUOOOOOssS",
        patternLetters = new RegExp("[" + letters1 + "]", "g"),
        lookupLetters = {}, letterTranslator;

    letters1.split("").forEach(function (letter, i) {
        lookupLetters[letter] = letters2[i];
    });

    letterTranslator = function(match) { 
        return lookupLetters[match] || match;
    };

    return function removeAccents(input) {
        return input.replace(patternLetters, letterTranslator);
    };
})();

// creates a specific filter function for use in List.js
function getAccentInsensitiveFilter(property, search) {
    search = removeAccents(search).toLowerCase();

    return function (item) {
        var value = removeAccents(item.values()[property] || "").toLowerCase();
        return value.indexOf(search) > -1;
    };
}

然后

// filter for "sunca" in the "featureName" property
yourList.filter(getAccentInsensitiveFilter("featureName", "șuncă"));

// remove filter 
yourList.filter();