Home > Enterprise >  Bold format certain string in shiny datatable using regex
Bold format certain string in shiny datatable using regex

Time:12-24

I have a datatable in a ShinyApp. This datatable has a column with multiple strings. I need to format one string pattern in this column to bold using regex. The following reprex needs to bold string "H2", but I need a regex solution. I know next to nothing about javascript, so any help is very much appreciated!

library(shiny)
library(DT)

data <- data.frame(V1 = 1:3, V2 = c("H1, H2, H3", "H5, H2, H6", "H4, H3, H5"))

ui <- fluidPage(
  "How can I make only 'H2' bold??",
  DTOutput("table", width = 500)
)

server <- function(input, output, session) {
  
  output$table <- renderDT(datatable(data))
  
}

shinyApp(ui, server)

CodePudding user response:

One option would be to use e.g. gsub to wrap the text you want bold inside an HTML b tag and set escape=FALSE in datatable():

library(shiny)
library(DT)

data <- data.frame(V1 = 1:3, V2 = c("H1, H2, H3", "H5, H2, H6", "H4, H3, H5"))

ui <- fluidPage(
  "How can I make only 'H2' bold??",
  DTOutput("table", width = 500)
)

server <- function(input, output, session) {
  
  output$table <- renderDT({
    data$V2 <- gsub("H2", "<b>H2</b>", data$V2)
    datatable(data, escape = FALSE)
  })
}

shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:5145

  • Related