Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace single quote with backslash single quote

Tags:

string

ruby

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.

like image 222
bobomoreno Avatar asked May 11 '12 13:05

bobomoreno


2 Answers

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
like image 60
steenslag Avatar answered Nov 20 '22 17:11

steenslag


The problem is that \' in a gsub replacement means "part of the string after the match".

You're probably best to use either the block syntax:

a = "Cote d'Ivoir"
a.gsub(/'/) {|s| "\\'"}
# => "Cote d\\'Ivoir"

or the Hash syntax:

a.gsub(/'/, {"'" => "\\'"})

There's also the hacky workaround:

a.gsub(/'/, '\#').gsub(/#/, "'")
like image 29
Chowlett Avatar answered Nov 20 '22 18:11

Chowlett