stringr::str_trim()
str_trim(string, side = "both") Returns:
character · Updated March 16, 2026 · Tidyverse stringr string whitespace tidyverse
The str_trim() function from stringr removes leading and trailing whitespace from strings. It is useful for cleaning user input, normalizing data, and preparing strings for display or further processing. Unlike base R’s trim.ws() which only works on vectors, str_trim is designed to work seamlessly with the tidyverse ecosystem and handles various edge cases gracefully.
Syntax
str_trim(string, side = "both")
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
string | character | Required | A character vector to trim |
side | character | ”both” | Which sides to trim: “both”, “left”, or “right” |
Examples
Basic usage
library(stringr)
# Trim whitespace from both ends
strings <- c(" hello ", " world", "test ")
str_trim(strings)
# [1] "hello" "world" "test"
Trimming only one side
# Trim only leading whitespace
str_trim(" hello", side = "left")
# [1] "hello"
# Trim only trailing whitespace
str_trim("hello ", side = "right")
# [1] "hello"
Cleaning data
library(dplyr)
# Example data with whitespace issues
df <- data.frame(
name = c(" John ", "Jane", " Bob "),
score = c(85, 92, 78)
)
df %>%
mutate(name = str_trim(name))
# name score
# 1 John 85
# 2 Jane 92
# 3 Bob 78
Combining with other string functions
# Normalize whitespace: trim and collapse multiple spaces
text <- c(" The quick brown fox ")
text %>%
str_trim() %>%
str_squish()
# [1] "The quick brown fox"
With readr and data import
library(readr)
# When importing CSV, whitespace is sometimes preserved
# str_trim cleans up the imported data
raw_data <- c(" 123 ", " 456 ", " 789 ")
str_trim(raw_data)
# [1] "123" "456" "789"
Handling different whitespace characters
# str_trim handles various whitespace types
messy <- c("\t text \n", " another ")
str_trim(messy)
# [1] "text" "another"
Common Use Cases
Form validation: Clean user-submitted data before validation
Data cleaning: Standardize imported data from spreadsheets or databases
Text preprocessing: Prepare text for NLP or analysis pipelines
Display formatting: Ensure consistent spacing in output tables or reports
See Also
- stringr::str_pad() — Add whitespace to strings to a fixed width
- stringr::str_c() — Combine multiple strings
- dplyr::mutate() — Transform columns including string cleanup