Wednesday, July 23, 2008

Decode-Encode in JavaScript/C#

This article basically focused on doing the encoding of special characters in JavaScript and its Decoding in C#. If we go for default libraries/functions provided in JavaScript/C#, then it skips some special characters while doing the Encode/Decode.


Note: To see the complete list of libraries/functions for Encode/Decode in JavaScript/C#, please refer the links provided (at last of this post) for reference purpose.
Following are the list of special characters and its corresponding encoded characters:



var Character = new Array('%', ' ', '~', '!', '@', '#', '$', '^', '&', '*', '(', ')', '{', '}', '[', ']', '=', ':', '/', ',', ';', '?', '+', '\'', '"', '\\');


 
var URLEncoded = new Array('%25', '%20', '%7E', '%21', '%40', '%23', '%24', '%5E', '%26', '%2A', '%28', '%29', '%7B', '%7D', '%5B', '%5D', '%3D', '%3A', '%2F', '%2C', '%3B', '%3F', '%2B', '%27', '%22', '%5C');




Following are the code snippet for Encoding special characters in JavaScript:



//Variable that contains special characters.
var strSample;
//Trim the string varibale.
strSample = strSample.replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1');
//Encode the string variable that contains special characters.
strSample = encodeURIComponent(strSample);
//Encode characters that are not covered in encodeURIComponent function.
var encodedCharacters = new Array('~', '!', '*', '(', ')', '\'');
var decodedCharacters = new Array('%7E', '%21', '%2A', '%28', '%29', '%60');
for(var i=0; i<encodedCharacters.length; i++)
{
strSample =
strSample.replace(encodedCharacters[i], decodedCharacters[i]);
}




Following are the code snippet for Decoding in C#:



//Following function Decode the encoded string,
//before that it replaces the “+” characters with “%2B”.
System.Web.HttpUtility.UrlDecode(strEncodedVariable.Replace("+", "%2B"));




Links for reference:
Comparing escape(), encodeURI(), and encodeURIComponent() --
http://xkr.us/articles/javascript/encode-compare/

INTRODUCTION TO URL ENCODING --
http://www.permadi.com/tutorial/urlEncoding/

The URLEncode and URLDecode Page --
http://www.albionresearch.com/misc/urlencode.php

MSDN HttpUtility.UrlEncode Method --
http://msdn2.microsoft.com/en-us/library/system.web.httputility.urlencode(vs.71).aspx

MSDN HttpUtility.UrlDecode Method (String) --
http://msdn2.microsoft.com/en-us/library/aa332862(VS.71).aspx

Encoding and Decoding URL strings --
http://www.kamath.com/codelibrary/cl006_url.asp

Google