Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to escape url with square brackets [ and ]?

Tags:

url

ruby

escaping

This url:

http://gawker.com/5953728/if-alison-brie-and-gillian-jacobs-pin-up-special-doesnt-get-community-back-on-the-air-nothing-will-[nsfw]

should be:

http://gawker.com/5953728/if-alison-brie-and-gillian-jacobs-pin-up-special-doesnt-get-community-back-on-the-air-nothing-will-%5Bnsfw%5D

But when I pass the first one into URI.encode, it doesn't escape the square brackets. I also tried CGI.escape, but that escapes all the '/' as well.

What should I use to escape URLS properly? Why doesn't URI.encode escape square brackets?

like image 945
foobar Avatar asked Oct 22 '12 14:10

foobar


2 Answers

You can escape [ with %5B and ] with %5D.

Your URL will be:

URL.gsub("[","%5B").gsub("]","%5D")

I don't like that solution but it's working.

like image 61
M_AWADI Avatar answered Nov 09 '22 11:11

M_AWADI


encode doesn't escape brackets because they aren't special -- they have no special meaning in the path part of a URI, so they don't actually need escaping.

If you want to escape chars other than just the "unsafe" ones, pass a second arg to the encode method. That arg should be a regex matching, or a string containing, every char you want encoded (including chars the function would otherwise already match!).

like image 26
cHao Avatar answered Nov 09 '22 11:11

cHao