代码之家  ›  专栏  ›  技术社区  ›  Tom M

DataTables全局正则表达式在每列中搜索

  •  0
  • Tom M  · 技术社区  · 5 年前

    我想实现一个功能,在这里你可以开始你的搜索字符串 $

    $('#myinput').on('keyup', (event) => {
        let searchValue = $(event.currentTarget).val();        
        if (searchValue.startsWith('$')) {
            searchValue = `^${searchValue.substr(1)}`;
        }
        this.dataTable.search(searchValue, true, false, false).draw();
    });
    

    但显然,这只在第一列中搜索。如果我不使用 ^ 在我的搜索中,它搜索所有列。如何检查列是否以开头 myValue

    可在上复制 https://datatables.net/examples/api/regex.html . 启用全局正则表达式并搜索^Airi和之后的^Accountant。

    我怎样才能找到 ^Accountant

    0 回复  |  直到 5 年前
        1
  •  1
  •   adelriosantiago    5 年前

    true 它将整行视为文本。因此,您的搜索应该如下所示:

    $('#myinput').on('keyup', (event) => {
        let searchValue = $(event.currentTarget).val();        
        if (searchValue.startsWith('$')) {
            searchValue = `\b${searchValue.substr(1)}`;
        }
        this.dataTable.search(searchValue, true, false, false).draw();
    });
    

    \b 代表“边界”。单词的每个开头都会创建一个新的边界(这里是Regex规范: https://regex101.com/r/s0MdwW/1

    只需要执行 ^ regex搜索(就像你现在的代码)但是

    enter image description here


    更新:好的,所以每列搜索肯定比预期的复杂,因为简单地搜索每列将创建一个AND搜索。例如,搜索“Airi”还需要“Airi”在 全部的

    要解决这个问题,必须建立一个自定义搜索函数。您可以在这里找到: https://codepen.io/adelriosantiago/pen/XWKGoLx?editors=1011

    $.fn.dataTable.ext.search.push 功能。