Similar to @Matthew_Plourde using gsub
However, using a pattern that will trim to zero characters i.e. return "" if the original string is shorter than the number of characters to cut:
cs <- c("foo_bar","bar_foo","apple","beer","so","a")
gsub('.{0,3}$', '', cs)
# [1] "foo_" "bar_" "ap" "b" "" ""
Difference is, {0,3}
quantifier indicates 0 to 3 matches, whereas {3}
requires exactly 3 matches otherwise no match is found in which case gsub
returns the original, unmodified string.
N.B. using {,3}
would be equivalent to {0,3}
, I simply prefer the latter notation.
See here for more information on regex quantifiers:
https://www.regular-expressions.info/refrepeat.html