Sean Sinykin
Sean Sinykin

Reputation: 552

R Shiny - How can I prepend a string to the beginning of every line of textAreaInput() in renderText() output?

I am developing an app to automate work processes, and I need to prepend the beginning of every line of user input with "#' ". So if user inputs:

Line1


Line4

I want the renderText() to display:

#' Line1


#' Line4

Below is simple code that needs to be altered to add the "#' " to the beginning of every line. I can add it to the first line, just not sure how to add to the rest.

if (interactive()) {

    ui <- fluidPage(
      textAreaInput("caption", "Caption", "Data Summary", width = "1000px"),
      verbatimTextOutput("value")
    )
    server <- function(input, output) {

        output$value <- renderText({ paste("#' ",input$caption, sep = "") })
    }
    shinyApp(ui, server)

}

Upvotes: 0

Views: 65

Answers (1)

amrrs
amrrs

Reputation: 6325

Regex based conditioned paste to rescue. Splits input character by new line and then prefixes '#' only if there's a letter or number and returns it with newlines and printed back to Shiny.

> if (interactive()) {
+     
+     ui <- fluidPage(
+         textAreaInput("caption", "Caption", "Data Summary", width = "1000px"),
+         verbatimTextOutput("value")
+     )
+     server <- function(input, output) {
+         
+         output$value <- renderText({ paste0(lapply(unlist(strsplit(input$caption,'\n')),function(x){ifelse(grepl('[A-z0-9]',x),paste0('#',x),x)}), collapse = '\n') })
+     }
+     shinyApp(ui, server)
+     
+ }

Upvotes: 1

Related Questions