Convert Integer to its Character Equivalent in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 the character's integer equivalent.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.