选择2自定义匹配器

Jas*_*oks 4 jquery jquery-select2

我正在尝试使用select2库的自定义匹配器.具体来说,我想返回othernot-found选项,以及只从字符串的开头匹配.我找到了以下问题,分别回答了这些部分:

选择2,当没有选项匹配时,应出现"其他"

jquery select2插件如何只得到结果'myString%'

但是,当我将这两种技术结合使用时,它就不再正确匹配.我的解决方案如下:

$("#myForm").select2({
    minimumInputLength: 2,
    width: width,
    matcher: function(term, text) {
        // THIS IS WHERE I COMBINE THE METHODS
        return text === 'Other' || text.toUpperCase().indexOf(term.toUpperCase())==0;
    },
    sortResults: function(results) {
        if (results.length > 1) results.pop();
            return results;
    }
});
Run Code Online (Sandbox Code Playgroud)

我做错了什么,以及使这个匹配器功能的正确方法是什么?

Jas*_*oks 5

我使用正则表达式并将条件||分成两个步骤来完成此操作.最终代码是:

$("#myForm").select2({
    minimumInputLength: 2,
    width: width,
    matcher: function(term, text) {
        var terms = term.split(" ");
        for (var i=0; i < terms.length; i++){
            var tester = new RegExp("\\b" + terms[i], 'i');
            if (tester.test(text) == false){
                return (text === 'Other')
            }
        }
        return true;
    },
    sortResults: function(results) {
        if (results.length > 1) {
            results.pop();
        }
        return results;
    },
});
Run Code Online (Sandbox Code Playgroud)