Drop all characters in string after specific character?

Viewed 47

The title speaks for it self. I've got this string

"Dog - food"

I want to drop all characters following the specific character "-"

Including the specific character chosen. This is my desired output

"Dog"

This is only a simple example. I intend to use this on much larger and dynamic strings.

2 Answers

I think that gsub function works fine for that action

gsub( " .*$", "", "Dog - food" )
## "Dog"

An option is word

library(stringr)
word(str1, 1)
#[1] "Dog"

Or with trimws from base R

trimws(str1, whitespace = "\\s*-.*")
#[1] "Dog"

data

str1 <- "Dog - food"
Related