How to add escape character with str_replace?

How to add escape character with stringr::str_replace(), stringr::str_replace_all()?

I need to replace characters such as ' or " in a string with \' (Can't -> Can\'t), but trying str_replace("Can't", "'", ("\'")) didn’t work.

>Solution :

The extra parentheses around the third argument in your function call str_replace("Can't", "'", ("\'")) do nothing. Instead, you need to escape the backslash, since it is a special character in R string literals. Furthermore, since it is also a special character in the str_replace replacement string, you need to escape it twice (\\\\\\\):

str_replace("Can't", "'", "\\\\'")

Leave a Reply