How can I convert a JavaScript string into a unique numeric value such that you can convert the numeric value back to the string? The length of the numeric value doesn\'t ma
A string can be described as a series of bytes with encoding. That results in characters being shown instead of the byte values.
to get the character code for a certain character you would call the charCodeAt
method on a string.
"a".charCodeAt(0); // => 97
"A".charCodeAt(0); // => 65
so as you can see there is a numeric value for each letter and it's variants. Now the next problem is how to store these numbers. For example you cannot just add them together because:
97 + 65 = 162;
String.fromCharCode(162); // => ¢
The best solution is probably to store them in an array so they can be easy reassembled later.
var StringTools = {
stringToNumbersArray: function(data){
return data.split('').map(function(c){return c.charCodeAt(0);});
},
numbersArrayToString: function(arr){
return arr.map(function(n){return String.fromCharCode(n)}).join('');
}
}
StringTools.stringToNumbersArray("Hello");
// => [72, 101, 108, 108, 111]
StringTools.numbersArrayToString([72, 101, 108, 108, 111])
// => "Hello"
Now it's entirely likely that you are wanting to support something that is not an array (a single string of numbers that reflects the entire word). To do this you need as many digits as would be required to store the largest value in the set, which is 3. So we can push these numbers together into a single number as long as we know this length and we can pull them apart later.
[72, 101, 108, 108, 111].reduce(function(memo, n){
return memo + ("000" + n).slice(-3);
}, "");
// => "072101108108111"
but as you can see this isn't a real number since the 0 at the beginning is a significant digit. More commonly hexadecimal is used to store these types of values. Consider that each number can be converted to hexadecimal using the toString
method where the argument is the radix (base of numbers, 16 for hex).
[72, 101, 108, 108, 111].reduce(function(memo, n){
return memo + ("00" + n.toString(16)).slice(-2);
}, "");
// => "48656c6c6f"
as you can see this saved us a few characters because we know that 4 bits can be stored in a single base 16 number (1111 === 15) and so you can get full byte of storage using just 2 base 16 numbers (16 * 16 = 256).
To reverse the hexadecimal code out to the original string you only need to split the string into pairs of 2 and convert them back to base 10, then use String.fromCharCode()
on the result to get each character.
"48656c6c6f".split("").reduce(function(result, c, idx, list){
if (idx % 2 != 0) {
result += String.fromCharCode(parseInt(list[idx-1] + c, 16));
}
return result;
}, "");