Datatables exact word search

前端 未结 3 1942
天命终不由人
天命终不由人 2020-12-11 23:32

Hi I\'m using datatables and I would like to filter my data by an exact word.

My table data looks like below;

+-----+----------+
| num | status   |
+         


        
相关标签:
3条回答
  • 2020-12-11 23:56

    To filter search result with an exact match could be done this way -

    table.column(index).search("^" + searchText + "$", true, false).draw();
    

    More info - https://stackoverflow.com/a/19114759/698127

    0 讨论(0)
  • 2020-12-12 00:15

    Hope this could help. Adding '\\b' at both end will let the table search for whole word only.

    var regex = '\\b' + searchKey + '\\b';
    <yourDataTable>.columns(<columnIndex>).search( regex, true, false).draw();
    
    0 讨论(0)
  • 2020-12-12 00:22

    If think you are better off with a custom filter for this task. unbind the default handlers and perform a exact match filter each time instead. If you have a table

    var table = $('#example').DataTable()  
    

    Then use a exact match custom filter this way

    $('.dataTables_filter input').unbind().bind('keyup', function() {
       var searchTerm = this.value.toLowerCase()
       if (!searchTerm) {
          table.draw()
          return
       }
       $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
          for (var i=0;i<data.length;i++) {
             if (data[i].toLowerCase() == searchTerm) return true
          }
          return false
       })
       table.draw();   
       $.fn.dataTable.ext.search.pop()
    })
    

    here is a demo -> http://jsfiddle.net/hmjnqjbs/1/ try search for tokyo.


    OK. I realize the question not is about "exact words" as in exact match filter, but more a whole word search. We want to see Vaio Q900 when we search on vaio, but we do not want to see VaioQ900 because Vaio here not is a whole word. This problem is simply solved by using a regex word boundary \b :

    $('.dataTables_filter input').unbind().bind('keyup', function() {
       var searchTerm = this.value.toLowerCase(),
           regex = '\\b' + searchTerm + '\\b';
       table.rows().search(regex, true, false).draw();
    })
    

    OP's fiddle from the comment below updated -> http://jsfiddle.net/hmjnqjbs/3/

    Now active, vaio and so on works as expected.

    0 讨论(0)
提交回复
热议问题