endsWith()

endsWith(x, suffix)
Returns: logical · Updated March 13, 2026 · String Functions
string pattern suffix endsWith base

The endsWith() function checks whether a character vector ends with a specified substring. It returns a logical vector indicating match status.

Syntax

endsWith(x, suffix)

Parameters

ParameterTypeDefaultDescription
xcharacterRequiredA character vector to check
suffixcharacterRequiredThe suffix to look for at the end of each string

Examples

Basic usage

# Check if strings end with a suffix
files <- c("data.csv", "script.R", "report.csv", "model.rds")

endsWith(files, ".csv")
# [1]  TRUE FALSE  TRUE FALSE

endsWith(files, ".R")
# [1] FALSE  TRUE FALSE FALSE

Case sensitivity

# These functions are case-sensitive
endsWith("file.CSV", ".csv")
# [1] FALSE

endsWith("file.csv", ".csv")
# [1] TRUE

Empty suffix

# Empty suffix matches everything
endsWith(c("a", "b", "c"), "")
# [1] TRUE TRUE TRUE

Common Patterns

File extension checking

# Validate file extensions
validate_extension <- function(filename, valid_ext) {
  ext <- paste0(".", valid_ext)
  endsWith(tolower(filename), tolower(ext))
}

validate_extension("document.PDF", "pdf")
# [1] TRUE

validate_extension("image.jpg", "png")
# [1] FALSE

Filtering by file type

# Get all CSV files
files <- c("data.csv", "report.csv", "script.R", "model.rds")
files[endsWith(files, ".csv")]
# [1] "data.csv"  "report.csv"

Path processing

# Check file paths
paths <- c("/home/user/file.txt", "/home/admin/data.csv", "/home/user/image.png")

# Find all files in a directory
endsWith(paths, "/data.csv")
# [1] FALSE  TRUE FALSE

See Also