Flangy > Software Development > ASP/VBScript > URLDecode
In ASP, the Server.URLEncode function takes a string and returns an escaped string usable as a URL or a querystring parameter. It converts space to + and other non-alphanumeric characters into % plus the hex digits of the character's ASCII value. ":" becomes "%3A". You can read about it in the URL RFC. (There may be RFCs that supercede that one, I'm not sure.)
Besides URLs, URLEncoded strings are also useful for turning strings into legal filenames. All the problem characters get encoded away, and % is a legal Win32 character name. If you use URLEncoded strings for that or other purposes, you'll sometimes find you want to decode back to the original string, say for printing back on a web page.
It appears that neither VBScript nor ASP provide a method to do this. I did a google search for "URLDecode VBScript" and saw a couple of implementations that I didn't care for, so here's my version:
' An inverse to Server.URLEncode
function URLDecode(str)
dim re
set re = new RegExp
str = Replace(str, "+", " ")
re.Pattern = "%([0-9a-fA-F]{2})"
re.Global = True
URLDecode = re.Replace(str, GetRef("URLDecodeHex"))
end function
' Replacement function for the above
function URLDecodeHex(match, hex_digits, pos, source)
URLDecodeHex = chr("&H" & hex_digits)
end function
This code uses a RegExp replacement function, which requires VBScript 5.5 or higher. Replacement functions are very poorly documented; they aren't even mentioned in the 5.6 RegExp.Replace reference page! But you can read all about them elsewhere on MSDN.
The key is that instead of passing a replacement string as the second parameter of .Replace(), you pass a function pointer. You can get a pointer to a function in VBScript by passing the name as a string to GetRef(). GetRef() was added to VBScript to allow dynamically assigned event handlers in the browser, but you can use it server-side as well.
I find this code to be a lot more concise than other URLDecode functions floating around out there. One of the top Google hits doesn't handle + correctly. And the use of replacement functions elimates the looping and concatenation that others use to convert the escape sequences. Some don't use regular expressions at all (possibly written prior to their addtion to VBScript), which means a lot of instr() and mid() calls.
Note: VBScript 5.6 has a function escape(), and a corresponding unescape(), but the docs for escape() specifically say it's not supposed to be used for URLs. unescape() mostly decodes a Server.URLEnocde string, but it doesn't convert + back to space. It would also decode 4 hex digit Unicode characters, which aren't part of the URL encoding scheme.