startsWith()

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

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

Syntax

startsWith(x, prefix)

Parameters

ParameterTypeDefaultDescription
xcharacterRequiredA character vector to check
prefixcharacterRequiredThe prefix to look for at the start of each string

Examples

Basic usage

# Check if strings start with a prefix
words <- c("apple", "apricot", "banana", "application")

startsWith(words, "app")
# [1]  TRUE  TRUE FALSE  TRUE

startsWith(words, "ban")
# [1] FALSE FALSE  TRUE FALSE

Case sensitivity

# These functions are case-sensitive
startsWith("Hello", "hello")
# [1] FALSE

startsWith("Hello", "Hello")
# [1] TRUE

Empty prefix

# Empty prefix matches everything
startsWith(c("a", "b", "c"), "")
# [1] TRUE TRUE TRUE

Common Patterns

Filtering data

# Filter rows based on prefix
df <- data.frame(
  name = c("user_data.csv", "report.pdf", "user_profile.csv", "notes.txt"),
  size = c(100, 250, 150, 50)
)

# Get only CSV files starting with "user_"
df[startsWith(df$name, "user_"), ]
#              name size
# 1  user_data.csv  100
# 3 user_profile.csv 150

Validation

# Check if column names start with a pattern
cols <- c("id", "name", "score_a", "score_b", "date")
startsWith(cols, "score_")
# [1] FALSE FALSE  TRUE  TRUE FALSE

String parsing

# Extract values with specific prefixes
lines <- c("ERROR: failed", "WARN: retry", "INFO: ok", "ERROR: crash")
error_lines <- lines[startsWith(lines, "ERROR:")]
error_lines
# [1] "ERROR: failed" "ERROR: crash"

See Also