bobomoreno
bobomoreno

Reputation: 2858

Replace single quote with backslash single quote

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.

Upvotes: 48

Views: 27928

Answers (3)

kukrt
kukrt

Reputation: 2207

# prepare a text file containing [  abcd\'efg  ]
require "pathname"
backslashed_text = Pathname("/path/to/the/text/file.txt").readlines.first.strip
# puts backslashed_text => abcd\'efg

unslashed_text = "abcd'efg"
unslashed_text.gsub("'", Regexp.escape(%q|\'|)) == backslashed_text # true
# puts unslashed_text.gsub("'", Regexp.escape(%q|\'|)) => abcd\'efg

Upvotes: 0

steenslag
steenslag

Reputation: 80105

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

Upvotes: 59

Chowlett
Chowlett

Reputation: 46685

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(/#/, "'")

Upvotes: 22

Related Questions