Replace single quote with backslash single quote

ruby, string

Solution

The %q delimiters come in handy here:

# %q(a string) is equivalent to a single-quoted string
puts "Cote d'Ivoir".gsub("'", %q(\\\')) #=> Cote d\'Ivoir

Problem

I have a very large string that needs to escape all the single quotes in it, so I can feed it to JavaScript without upsetting it. I have no control over the external string, so I can't change the source data. Example: ``` Cote d'Ivoir -> Cote d\'Ivoir ``` (the actual string is very long and contains many single quotes) I'm trying to this by using `gsub` on the string, but can't get this to work: ``` a = "Cote d'Ivoir" a.gsub("'", "\\\'") ``` but this gives me: ``` => "Cote dIvoirIvoir" ``` I also tried: ``` a.gsub("'", 92.chr + 39.chr) ``` but got the same result; I know it's something to do with regular expressions, but I never get those.

Original source