Highlight the matched filter in a cell in Tabulator.js

I could not find a proper way to highlight your matches in a cell when you apply column filters. This is what I came up with, but it might not be the best way. I would actually expect this to be build in. But let me know if you have a better solution for this.

table.on('dataFiltered', function (filters, rows): any {
    table.getRows().forEach((r) => {
      r.getCells().forEach((c) => {
        c.setValue(c.getValue())
      })
    })
    rows.forEach((row) => {
      if (!filters.length) return
      filters.forEach((filter) => {
        const cell = row.getCell(filter.field)
        cell.getElement().innerHTML = highlight(
          cell.getValue(),
          filter.value
        )
      })
    })
  })

function highlight(inputString: string, substring: string) {
  var regex = new RegExp(substring, 'gi')
  var resultString = inputString.replace(
    regex,
    '<span style="background-color:yellow;border:1px solid lightgrey">$&</span>'
  )
  return resultString
}

Leave a Comment