Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight word in DT in shiny based on regex

Tags:

Using DT in shiny, I want to be able to highlight the selected word. Setting searchHighlight = TRUE is close to what I want, but this will also highlight words that include the search. For example, if I am searching for "on" it will also match "stone", highlighting the "on" in the middle.

EXAMPLE IMAGE:

Words within words being highlighted

I can refine the search options so regex = TRUE, but then no highlighting occurs. This is also true if I want to use regex like "on|in", for example.

EXAMPLE (including regex):

library(shiny)
library(DT)
library(data.table)

example_data <- data.table(words = c("on", "scone", "wrong", "stone"), 
                           description = c("The word on", "Scone is not on.", "Not on either", "Not here at all"))

ui = shinyUI(fluidPage(

  sidebarLayout(
    sidebarPanel(
      textInput("word_select", label = "Word to search")
      ),
    mainPanel(
      dataTableOutput("word_searched")
    )
  )
))

server = shinyServer(function(input, output, session) {

  output$word_searched <- renderDataTable({
    datatable(
      example_data, 
      options = list(searchHighlight = TRUE, 
                     search = list(regex = TRUE, 
                                   search = paste0("\\b", tolower(input$word_select), "\\b")))
    )
  })

  })

shinyApp(ui = ui, server = server)

The DT is already being filtered on the word by a reactive expression, so all the fields will definitely include the selected word, but I just want to avoid confusion from users thinking that longer words are being included in the search erroneously. I haven't done this in the example but just confirming this is not the element I'm concerned about.

Thanks for your help.

(EDITED to add an example of a word with punctuation in the example data.)