Friday, January 2, 2009

How do I decode an encoded URL

How do I decode an encoded URL?
This question has been asked frequently (and variants of 'decode' keep showing up in this site's search logs). While the Server object provides a Server.URLEncode() method, they didn't bother providing a Server.URLDecode() or Server.URLUnEncode() method. I assume they didn't think it would ever be needed, but they were wrong... I've been in a few situations where this function would have been very handy. Here are both URLEncode and URLDecode functions (for completeness) in VBScript and JScript:

In VBScript:

<%
Function URLDecode(str)
str = Replace(str, "+", " ")
For i = 1 To Len(str)
sT = Mid(str, i, 1)
If sT = "%" Then
If i+2 < Len(str) Then
sR = sR & _
Chr(CLng("&H" & Mid(str, i+1, 2)))
i = i+2
End If
Else
sR = sR & sT
End If
Next
URLDecode = sR
End Function

Function URLEncode(str)
URLEncode = Server.URLEncode(str)
End Function

str1 = "http://www.foo.com/blah.asp?foo=1 & 2 &g=0"
str2 = URLEncode(str1)
str3 = URLDecode(str2)
Response.Write(str1 & "
" & str2 & "
" & str3)
%>

And here in JScript:

<script language=JScript runat=server>

function URLDecode(str)
{
return unescape(str);
}

function URLEncode(str)
{
str = escape(str);

// JScript doesn't think '/' needs to be escaped...
// I'm not sure it does either, but take it out to be
// consistent with VBScript's built-in URLEncode()

while (str.indexOf("/")!=-1)
{
str = str.replace("/","%2F");
}
return str;
}

var str1 = "http://www.foo.com/blah.asp?foo=1 & 2 &g=0";
var str2 = URLEncode(str1);
var str3 = URLDecode(str2);
Response.Write(str1 + "
" + str2 + "
" + str3)

</script>

No comments: