I want to convert an integer into its character equivalent based on the alphabet. For example:
0 => a
1 => b
2 => c
3 => d
etc.
Assuming you want lower case letters:
var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...
97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if n > 25
, you will get out of the range of letters.
Try
(n+10).toString(36)
chr = n=>(n+10).toString(36);
for(i=0; i<26; i++) console.log(`${i} => ${ chr(i) }`);
A simple answer would be (26 characters):
String.fromCharCode(97+n);
If space is precious you could do the following (20 characters):
(10+n).toString(36);
Think about what you could do with all those extra bytes!
How this works is you convert the number to base 36, so you have the following characters:
0123456789abcdefghijklmnopqrstuvwxyz
^ ^
n n+10
By offsetting by 10 the characters start at a
instead of 0
.
Not entirely sure about how fast running the two different examples client-side would compare though.
Javascript's String.fromCharCode(code1, code2, ..., codeN) takes an infinite number of arguments and returns a string of letters whose corresponding ASCII values are code1, code2, ... codeN. Since 97 is 'a' in ASCII, we can adjust for your indexing by adding 97 to your index.
function indexToChar(i) {
return String.fromCharCode(i+97); //97 in ASCII is 'a', so i=0 returns 'a',
// i=1 returns 'b', etc
}
I don't like all the solutions that use magic numbers like 97
or 36
.
const A = 'A'.charCodeAt(0);
let numberToCharacter = number => String.fromCharCode(A + number);
let characterToNumber = character => character.charCodeAt(0) - A;
this assumes uppercase letters and starts 'A' at 0.
Will be more portable in case of extending to other alphabets:
char='abcdefghijklmnopqrstuvwxyz'[code]
or, to be more compatible (with our beloved IE):
char='abcdefghijklmnopqrstuvwxyz'.charAt(code);