Last updated: Mar 4, 2024
Reading timeยท2 min
Use the String.fromCharCode()
method to increment a letter in JavaScript.
The String.fromCharCode
method takes numbers that represent code units as
parameters and returns the corresponding characters.
function getNextChar(char) { return String.fromCharCode(char.charCodeAt(0) + 1); } console.log(getNextChar('a')); // ๐๏ธ b console.log(getNextChar('A')); // ๐๏ธ B
The String.fromCharCode() method takes one or more code units as parameters.
We used the String.charCodeAt() method to get the code unit of the character.
The method takes the index of the character in the string as a parameter.
console.log('a'.charCodeAt(0)); // ๐๏ธ 97 console.log('A'.charCodeAt(0)); // ๐๏ธ 65
The last step is to increment the character's code unit by 1
to get the next
letter.
z
as a parameter because you'd get a special character back.z
To handle this scenario, we can check if the supplied character is upper or
lowercase z
and return a different result.
For example, we could roll over and return a
or A
.
function getNextChar(char) { if (char === 'z') { return 'a'; } if (char === 'Z') { return 'A'; } return String.fromCharCode(char.charCodeAt(0) + 1); } console.log(getNextChar('z')); // a console.log(getNextChar('Z')); // A
The 2 if
statements check if the provider character is lowercase or uppercase
z
.
You might have to handle this differently, e.g. return the character as is, if
the user passed z
.
Use the String.fromCharCode()
method to decrement a letter in JavaScript.
The String.fromCharCode
method takes numbers that represent code units as
parameters and returns the corresponding characters.
function getPrevChar(char) { return String.fromCharCode(char.charCodeAt(0) - 1); } console.log(getPrevChar('z')); // y console.log(getPrevChar('Z')); // Y
Instead of adding 1
to the character code, we subtract 1
to get the previous
character.
You might have to handle the scenario where lowercase or uppercase a
is
provided to the function.
With the current implementation, the function would return a backtick character.
If a
is supplied, this code sample returns z
.
function getPrevChar(char) { if (char === 'a') { return 'z'; } if (char === 'A') { return 'Z'; } return String.fromCharCode(char.charCodeAt(0) - 1); } console.log(getPrevChar('a')); // z console.log(getPrevChar('A')); // Z
It might make more sense in your use case to just return the supplied character
if it's a
.
This is entirely application-dependent.
I've also written an article on how to convert an integer to its character equivalent.