rguides

stringr::str_trim()

str_trim(string, side = "both")

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 smoothly with the tidyverse ecosystem and handles various edge cases gracefully.

Syntax

str_trim(string, side = "both")

Parameters

ParameterTypeDefaultDescription
stringcharacterRequiredA character vector to trim
sidecharacter”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"

By default str_trim() removes whitespace from both ends of each string in the input vector. The function is vectorised, so passing a character vector with multiple elements trims all of them at once without needing an explicit loop or lapply() call.

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"

When you only need to clean up leading whitespace from a text column, setting side = "left" preserves any trailing formatting that might be intentional. Similarly, using side = "right" removes only trailing whitespace while keeping leading indentation intact for each element.

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

Applying str_trim() inside dplyr::mutate() is a standard first step when importing data from CSV files or spreadsheets where leading and trailing spaces often sneak into text columns unnoticed. Trimming early in the pipeline prevents mismatches during joins and filters, because "John " and "John" are treated as different values by R.

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"

The combination of str_trim() followed by str_squish() produces clean, single-spaced text by first stripping edge whitespace and then collapsing any remaining runs of internal spaces into one. This two-step process is ideal for preparing free-text fields for analysis or display purposes.

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"

When importing data with readr or similar packages, column values sometimes retain surrounding whitespace from the source file. Applying str_trim() immediately after import normalises the data and prevents subtle bugs where trailing spaces cause values that look identical to be treated as distinct.

Handling different whitespace characters

# str_trim handles various whitespace types
messy <- c("\t  text  \n", "  another  ")
str_trim(messy)
# [1] "text"      "another"

str_trim() handles all Unicode whitespace characters including tabs, newlines, and non-breaking spaces, not just the standard ASCII space character. This means the function works reliably on text originating from web pages, word processors, or international sources where varied whitespace characters are common.

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

stringr::str_trim() in practice

str_trim() removes whitespace from the start and end of strings. The side argument controls which end: "both" (default), "left", or "right". Whitespace includes spaces, tabs, newlines, and other Unicode whitespace characters.

str_trim() is the stringr equivalent of base R’s trimws(). Both work the same way: str_trim(x, side = "both") matches trimws(x, which = "both"). Use str_trim() in tidyverse pipelines for consistency; use trimws() when avoiding package dependencies.

A related function, str_squish(), goes further than trimming: it removes leading and trailing whitespace and collapses internal whitespace sequences to a single space. str_squish(" hello world ") returns "hello world". Use str_squish() when cleaning free-text input where inconsistent spacing is expected throughout the string.

Trimming is a standard first step when reading data from CSV files, user input, or scraped text. Column values with leading or trailing spaces will not match in joins or filter conditions: "Alice " and "Alice" are not equal. Always trim string columns after import when the source may have whitespace irregularities.

str_trim() vectorizes over string and handles NA by returning NA. It is type-stable: input and output are both character vectors.

See also