Friday, June 29, 2012

Javascript : Encode special characters

In Javascript, you may required to escape special characters from a text at some point of time and later you may need to retrieve the original text. This may be because of some logic or for passing as argument in some function. The basic is very simple we will write a encode function which will encode the special characters and a decode function which will get the original text out of encoded text.

Please use the below functions in your code accordingly.

<script language="Javascript">


   var toEncode = new Array(" ","!","@","#","$","%","^","&","*","(",")","-","_","=","+",":","\;",".","\"","'","\\","/","?","<",">","~","[","]","{","}","`");
 var toDecode = new Array("%20","%21","@","%23","%24","%25","%5E","%26","*","%28","%29","-","_","%3D","+","%3A","%3B",".","%22","%27","%5C","/ /","%3F","%3C","%3E","%7E","%5B","%5D","%7B","%7D","%60");

 function encode(val)
 {
  for (var i = 0; i < toEncode.length; i++)
  {
   val = val.replace(toEncode[i],toDecode[i]);
  }
  
  return val;
 }

 function decode(val)
 {
  for (var i = toDecode.length; i >= 0; i--)
  {
   val = val.replace(toDecode[i],toEncode[i]);
  }
  
  return val;
 }

</script>