【问题标题】:select2 search match with typed letter in any position regexselect2 搜索与任何位置正则表达式中键入的字母匹配
【发布时间】:2020-03-09 20:58:00
【问题描述】:

有没有办法在select2 中搜索任何匹配的字母?

例如,如果我有以下选项:

<option value="MANGO">MANGO</option>
<option value="ORANGE">ORANGE</option>
<option value="APPLE">APPLE</option>

如果我输入“mngo”,有没有办法在搜索结果中显示“MANGO”选项?

【问题讨论】:

    标签: javascript jquery html regex jquery-select2


    【解决方案1】:

    正则表达式很清楚,它在每个字符之间以及所有字符之前和之后添加.*。您可以随意更改该通配符。

    我尽量不那么冗长,这样做既棘手又有趣。

    $('#select2').select2({
      matcher: function(term, text) {
        // If search is empty we return everything
        if ($.trim(term.term) === '') return text;
    
        // Compose the regex
        var regex_text = '.*';
        regex_text += (term.term).split('').join('.*');
        regex_text += '.*'
    
        // Case insensitive
        var regex = new RegExp(regex_text, "i");
    
        // If no match is found we return nothing
        if (!regex.test(text.text)) {
          return null;
        }
    
        // Else we return everything that is matching
        return text;
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
    
    <select id="select2" style="width:100%;">
      <option value="MANGO">MANGO</option>
      <option value="ORANGE">ORANGE</option>
      <option value="APPLE">APPLE</option>
    </select>

    【讨论】:

      猜你喜欢
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2022-08-03
      相关资源
      最近更新 更多