R Program to Trim Leading and Trailing Whitespaces

Example 1: Remove Whitespaces in R

text1 <- "     Programiz Pro         "
 
# remove whitespaces using trimws()
print(trimws(text1))

Output

[1] "Programiz Pro"

In the above example, we have used the trimws() function to remove the leading and trailing whitespace. It doesn't remove whitespace that appears in the middle.


Example 2: Remove Leading Whitespaces in R

text1 <- "     Programiz Pro         "
 
# remove leading whitespaces using trimws()
print(trimws(text1, "l"))

Output

[1] "Programiz Pro         "

In the above example, we have passed "l" inside the trimws() function to remove the leading whitespaces in the text1 string.


Example 3: Remove Trailing Whitespaces in R

text1 <- "     Programiz Pro         "
 
# remove trailing whitespaces using trimws()
print(trimws(text1, "r"))

Output

[1] "     Programiz Pro"

In the above example, we have passed "r" inside the trimws() function to remove the trailing whitespaces in the text1 string.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges