Convert Integer to its Character Equivalent in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 03 20212 min read

Convert Integer to its Character Equivalent #

To convert an integer to its character equivalent, add the character code of the letter a (97) to the integer and pass the result as a parameter to the String.fromCharacterCode() method. The String.fromCharCode will return the character equivalent of the integer.

index.js
function intToChar(int) { // ๐Ÿ‘‡๏ธ for Uppercase letters, replace `a` with `A` const code = 'a'.charCodeAt(0); console.log(code); // ๐Ÿ‘‰๏ธ 97 return String.fromCharCode(code + int); } console.log(intToChar(0)); // ๐Ÿ‘‰๏ธ "a" console.log(intToChar(4)); // ๐Ÿ‘‰๏ธ "e"

We used the String.charCodeAt to get the character code of the letter a, which is 97.

The only parameter the charCodeAt method takes is the index of the string for which to get the character code.

If you need to convert the integer to an uppercase character, get the character code of the letter A instead (65).
index.js
function intToChar(int) { const code = 'A'.charCodeAt(0); console.log(code); // ๐Ÿ‘‰๏ธ 65 return String.fromCharCode(code + int); } console.log(intToChar(0)); // ๐Ÿ‘‰๏ธ "A" console.log(intToChar(4)); // ๐Ÿ‘‰๏ธ "E"

The last step is to use the String.fromCharCode to get the character equivalent of the integer.

The method takes one or more numbers as parameters, and returns a string containing the code units for the numbers.

By adding the character code of the letter a to the integer, we start counting from 0, where 0 is a, 1 is b, etc.

You can convert the character back to an integer, by using the charCodeAt method.

index.js
function charToInt(char) { const code = 'a'.charCodeAt(0); console.log(code); return char.charCodeAt(0) - code; } console.log(charToInt('a')); // ๐Ÿ‘‰๏ธ 0 console.log(charToInt('e')); // ๐Ÿ‘‰๏ธ 4

We subtracted the character code of the letter a from the character code of the supplied character to get back the character's integer equivalent.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee