Search code examples
rdatatablesdt

Search with or without regular expression with a 'DT' table


With the DT package, it is possible to search in a table with regular expressions:

datatable(
  data = iris,
  options = list(
    search = list(regex = TRUE)
  )
)

But I would like to have the possibility to search with or without a regular expression.


Solution

  • I think the best way to go is to use the SearchBuilder extension.

    The SearchBuilder extension already defines numerous useful search criteria for strings, such as "contains", "starts with", "ends with", etc. And you can add a custom criterion if you want. Here I've added a criterion "matches regex", which allows to search with a regular expression:

    library(DT)
    
    datatable(
      iris,
      extensions = "SearchBuilder",
      options = list(
        dom = "Qlfrtip",
        searchBuilder = list(
          conditions = list(
            string = list(
              regex = list(
                conditionName = "matches regex",
                init = JS(
                  "function (that, fn, preDefined = null) {",
                  "  var el =  $('<input/>').on('input', function() { fn(that, this) });",
                  "  if (preDefined !== null) {",
                  "     $(el).val(preDefined[0]);",
                  "  }",
                  "  return el;",
                  "}"
                ),
                inputValue = JS(
                  "function (el) {",
                  "  return $(el[0]).val();",
                  "}"
                ),
                isInputValid = JS(
                  "function (el, that) {",
                  "  return $(el[0]).val().length !== 0;",
                  "}"
                ),
                search = JS(
                  "function (value, regex) {",
                  "  var reg = new RegExp(regex, 'g');",
                  "  return reg.test(value);",
                  "}"
                )
              )
            )
          )
        )
      )
    )
    

    enter image description here