Unencoding encoded URLs in a function

There's also an internal function that does it:

ExternalService`DecodeString["https%3A%2F%2Fwww.google.co.uk%2Fimages%2Fsrpr%2Flogo4w.png"]

At one time, the implementation of that function used J/Link code similar to Albert's code above, but now it is done in top-level Mathematica.

ExternalService`EncodeString does URL-encoding, if you want to go in the other direction.


There might be undocumented internal functions burried somewhere to do this, but it is relatively straightforward to get a result via JLink:

Needs["JLink`"];
InstallJava[];
LoadJavaClass["java.net.URLDecoder"];
url = "https%3A%2F%2Fwww.google.co.uk%2Fimages%2Fsrpr%2Flogo4w.png";
java`net`URLDecoder`decode[url]

see the Java documentation for more information about the java.net package and the java.net.URLDecoder class. The class java.net.URLEncoder might also be of interest...

With the information in e.g. wikipedia about "percent encoding" and the links to the relevant RFCs it is actually not difficult to build something based on StringReplace -- as J.M.'s answer shows in a very elegant way.


Works nicely:

PercentDecode[s_String] := StringReplace[s, RegularExpression["%([[:xdigit:]]{2})"] :> 
                                         FromCharacterCode[FromDigits["$1", 16]]]

PercentEncode[s_String] := StringReplace[s, {" " -> "+", 
   RegularExpression["[^\\w/\\?=:._~]"] :> 
    StringJoin["%", ToUpperCase[IntegerString[First[ToCharacterCode["$0"]], 16]]]}]

Test:

PercentDecode["http://www.test.com/~a_b?i=Cos%5B2%5D"]
   "http://www.test.com/~a_b?i=Cos[2]"

PercentEncode["http://www.test.com/~a_b?i=Cos[2]"]
   "http://www.test.com/~a_b?i=Cos%5B2%5D"