Last updated: Mar 4, 2024
Reading timeยท2 min
To convert an integer to its character equivalent:
charCodeAt()
method to get the character code of the letter a
.fromCharCode()
method with the sum of the integer and the
character code.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
.
The character code of a
is 97
.
console.log('a'.charCodeAt(0)); // ๐๏ธ 97
The only parameter the charCodeAt
method takes is the index of the character
in 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).
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"
Notice that we called the String.charCodeAt
method on a capital letter A
to
convert the integer to its uppercase character equivalent.
The last step is to use the String.fromCharCode() method to get the character equivalent of the integer.
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.
To convert a character back to its integer equivalent:
charCodeAt
method to get the UTF-16 code unit of the letter a
.charCodeAt
method to get the code unit of the character.a
from the code unit of the character.function charToInt(char) { const code = 'a'.charCodeAt(0); return char.charCodeAt(0) - code; } console.log(charToInt('a')); // ๐๏ธ 0 console.log(charToInt('e')); // ๐๏ธ 4
The first step is to get the UTF-16 code unit of the letter a
.
Then, we subtract the character code of the letter a
from the character code
of the supplied character.
The function returns the integer equivalent of the character.
You can learn more about the related topics by checking out the following tutorials: