I have the following scenario: I need to encode my string then i have to decode my value.
The encoded string should have the same length as the string itself. My input string has only = Alpha & Number values.
For example :
String="Test12345" (lenght : 9)
Encode = (encode should lenght 9)
Decode = Test12345
I tried different CharcodeAt , FromCharCode function but I'm getting longer Encoded strings. I could not find the solution.
See the output values which i write code:
1. Your Input String:
Test12345
2. Encoded String:
4R4A3W3V5Q5P5O5N5M
3. Result : Decoded/Actual Input String:
Test12345
code :
String.prototype.toEncodedString = function()
{
var ostr=this.toString().replace(/\s+/g,'');
var x,nstr='',len=ostr.length;
for(x=0;x<len;++x)
{
nstr+=(255-ostr.charCodeAt(x)).toString(36).toUpperCase();
};
return nstr;
};
String.prototype.fromEncodedString = function() {
var ostr=this.toString();
var x,nstr='',len=ostr.length;
for(x=0;x<len;x+=2)
{
nstr+=String.fromCharCode(255-parseInt(ostr.substr(x,2),36));
};
return nstr;
};
Could anyone help me on this.
fromCharCode()instead oftoString(). You're converting each encoded character to the base-36 value of its char code.