Search code examples
rgsubspacing

Remove multiple spaces but leave single space in R


I have text like below.

"The comm   unity is here to help you wi   th specific co   ding"

And I want to remove triple spaces in the sentence while leaving single space.

I tried

gsub(text, "   ", "")

but it doesn't work.


Solution

  • To remove exactly three spaces inside a word use:

    x <- "The comm   unity is here to help you wi   th specific co   ding"
    output <- gsub("\\b[ ]{3}\\b", "", x)
    output
    
    [1] "The community is here to help you with specific coding"