6

Any idea how I can unescape the following string in Ruby?

C:\inetpub\wwwroot\adminWeb

to

C:\inetpub\wwwroot\adminWeb

or to

C%3A%5Cinetpub%5Cwwwroot%5CadminWeb

Tried with URI.decode with no success.

3 Answers 3

21

The CGI library is one option:

require 'cgi'

CGI.unescapeHTML('C:\inetpub\wwwroot\adminWeb')
# => "C:\\inetpub\\wwwroot\\adminWeb"
0
6

One more variant is HTMLEntities

HTMLEntities.new.decode "C:\inetpub\wwwroot\adminWeb"             
# => "C:\\inetpub\\wwwroot\\adminWeb"

I prefer to use it because it deals with rare cases aså and — which CGI.unescapeHTML does not

1

An alternative is using the standard lib's URI module:

require 'uri'
URI.unescape "C%3A%5Cinetpub%5Cwwwroot%5CadminWeb" # => "C:\\inetpub\\wwwroot\\adminWeb"

EDIT This is answer is obsolete. Please check this thread.

1
  • URI.unescape (now obsolete) will decode %-escaped characters in URLs. That's different from decoding HTML entities (&...;).
    – Lennart L
    Oct 22, 2023 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.