You can get the ASCII value of a character with .charCodeAt(position)
. You can split a character into multiple characters using this.
First, get the char code for every character, by looping trough the string. Create a temporary empty string, and while the char code is higher than 255 of the current character, divide 255 from it, and put a ÿ
(the 256th character of the extended ASCII table), then once it's under 255 use String.fromCharCode(charCode)
, to convert it to a character, and put it at the end of the temporary string, and at last, replace the character with this string.
function encode(string) {
var result = [];
for (var i = 0; i < string.length; i++) {
var charCode = string.charCodeAt(i);
var temp = "";
while (charCode > 255) {
temp += "ÿ";
charCode -= 255;
}
result.push(temp + String.fromCharCode(charCode));
}
return result.join(",");
}
The above encoder puts a comma after every group, this could cause problems at decode, so we need to use the ,(?!,)
regex to match the last comma from multiple commas.
function decode(string) {
var characters = string.split(/,(?!,)/g);
var result = "";
for (var i = 0; i < characters.length; i++) {
var charCode = 0;
for (var j = 0; j < characters[i].length; j++) {
charCode += characters[i].charCodeAt(j);
}
result += String.fromCharCode(charCode);
}
return result;
}