Monday, May 12, 2008

Url Encoder/Decoder


Description


This articles shows you how to encode and decode posted form data from the browser to a webserver via "GET" method. Most people rely on the Javascript methods, escape and unescape, to format this data. The only problem is that they encode the space character as "%20" and treat "+" as a safe character. Copy and paste the code into an external javascript file called codeapedia.url.js


Code

/**
* @projectDescription Url encoder/decoder
*
* @author Ryan Estes http://www.codeapedia.com
* @version 0.3
*/

var url =
{
/**
* Url encodes a string
* @return {string}
*/

encode : function(pValue)
{
var str = escape(pValue);
str = str.replace(/\+/g,"%2B");
str = str.replace(/%20/g,"+");
return str;
},
/**
* Decodes a url encoded string
* @return {string}
*/

decode : function(pValue)
{
var str = pValue.replace(/\+/g," ");
str = unescape(str);
return str;
}
}

Example

<script type="text/javascript" language="javascript" >
var strUrl = "http://www.mydomain.com/?lang=";
strUrl = strUrl + url.encode("ASP.NET 2.0,C# 2.0");
alert(strUrl);
alert(url.decode(strUrl));
</script>

The above example above will alert

  1. http://www.mydomain.com/?lang=ASP.NET+2.0%2CC%23+2.0

  2. http://www.mydomain.com/?lang=ASP.NET 2.0,C# 2.0


0 comments:

 

blogger templates | Make Money Online