Encoding and Decoding URL strings
by Manohar Kamath
August 31, 1999
When you pass something as an URL's querystring, the string is
encoded and all special characters like space, %, etc. are converted into their %xx
values. Here, xx denotes a number and the %xx represents any character that can not be
passed within the URL in their original form. The characters include spaces, all
punctuation symbols, accented characters (like å, õ, etc.) and non-ASCII
characters(Source: MSDN library).
The URL has to be in one piece and symbols spaces can break it.
Also, symbols like &, = and + are used within an URL to separate the querystring's
key. So, if you want to pass a key-value pair something like Message=Hello World, the URL
(when not encoded) may look like:
and the space between "Hello" and "World"
breaks the URL. So when you do something like
within mypage.asp, you will get only "Hello"
and special characters into their %xx equivalents. This function is very useful when you
are trying to "build" a URL from within your ASP page. So if you want to build a
correct version of the URL shown in listing 1, you would do something like in listing 3
lsURL = "mypage.asp?message=" + escape("Hello World!")
Alternatively, you can use the URLEncode function in the Server
object to get the same results. Listing 4 is in VBScript.
lsURL = "mypage.asp?message=" & Server.URLEncode("Hello World!")
The result is mypage.asp?message=Hello%20World%21
Decoding the querystring is easy - just call unescape() function
Note: You will need to call
unescape() within the same page as you called escape() to decode the strings. Otherwise, a
simple Request.QueryString("message") will automatically decode the URL for you.
I wrote this tiny function so you can include it on any ASP page
with any scripting language and use it. Just include it in any ASP page and call the
function URLEncode() with a string argument.
An example of using this is in Listing 6
the result being - Hello World!
Some people have asked me how to decode those "+"s, which are nothing but
encoded spaces in the URL. Although Request.QueryString("your_key") should
remove the +s, here is the code that will replace +s with spaces. This is nothing but a
modified Listing 5.
var lsRegExp = /\+/g;
return unescape(String(psEncodeString).replace(lsRegExp, " "));