73

How do I transform

www.bestbuy.com/site/Electronics\Audio\abcat0200000.c=3fid=3dabcat0200000

into its original format?

www.bestbuy.com/site/Electronics/Audio/abcat0200000.c?id=abcat0200000

Is there a urldecode?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
wefwgeweg
  • 1,359
  • 3
  • 11
  • 15

4 Answers4

184

A better method is CGI.unescape:
URI.unescape is deprecated

decoded_uri = CGI.unescape(encoded_uri)
merqlove
  • 3,674
  • 1
  • 23
  • 22
  • 3
    Why not use `CGI.unescape` instead? – Islam Azab Dec 28 '14 at 13:41
  • 6
    From the latest Ruby docs for [`URI.unescape`](http://ruby-doc.org/stdlib-2.5.1/libdoc/uri/rdoc/URI/Escape.html): "This method is obsolete and should not be used. Instead, use [CGI.unescape](https://ruby-doc.org/stdlib-2.5.1/libdoc/cgi/rdoc/CGI/Util.html#method-i-unescape), [URI.decode_www_form](http://ruby-doc.org/stdlib-2.5.1/libdoc/uri/rdoc/URI.html#method-c-decode_www_form) or [URI.decode_www_form_component](http://ruby-doc.org/stdlib-2.5.1/libdoc/uri/rdoc/URI.html#method-c-decode_www_form_component) depending on your specific use case." – take Aug 31 '18 at 20:21
37

Via decode:

require 'uri'
URI.decode(encoded_uri)

Ruby 2.7 and above:

require 'uri'
URI.decode_www_form_component(encoded_uri)
tokhi
  • 21,044
  • 23
  • 95
  • 105
  • 1
    this method is also deprecated according to [RuboCop](https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Lint/UriEscapeUnescape), [take](https://stackoverflow.com/users/2946687/take)'s comment applies here as well: `URI.decode_www_form` or `URI.decode_www_form_component` should be used instead. – SMAG Jan 05 '21 at 21:13
23

The equivalent of PHP's urldecode in Ruby is CGI::unescape.

Robert Speicher
  • 15,382
  • 6
  • 40
  • 45
7

Well the thing with =3f and =3d is quoted-printable encoding. Ruby can decode it with the .unpack("M") method.

The backslashes? They're just weird and wrong. It would probably be safe to string-replace them to / since backslash should not be in a URL to begin with.

bobince
  • 528,062
  • 107
  • 651
  • 834