How to Increment/Decrement Letters in JavaScript

avatar

Borislav Hadzhiev

Tue Nov 16 20212 min read

banner

Photo by Matthew Henry

Increment Letters in JavaScript #

Use the String.fromCharCode() method to increment a letter in JavaScript, e.g. String.fromCharCode(char.charCodeAt(0) + 1). The String.fromCharCode method takes numbers that represent code units as parameters and returns the corresponding characters.

index.js
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 numbers.

To get the code unit of the character, we use the charCodeAt method, which takes the index of the character in the string as a parameter.

index.js
console.log('a'.charCodeAt(0)); // ๐Ÿ‘‰๏ธ 97 console.log('A'.charCodeAt(0)); // ๐Ÿ‘‰๏ธ 65

The last step is to increment the character code by 1 to get the next letter.

This would not work as expected if you provide z as a parameter, because you'd get special character back.

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.

index.js
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

We added 2 if statements that check if the provided character is lowercase or uppercase z. You might have to handle this differently, e.g. return the character as is, if the user supplied z.

Decrement Letters in JavaScript #

Use the String.fromCharCode() method to decrement a letter in JavaScript, e.g. String.fromCharCode(char.charCodeAt(0) - 1). The String.fromCharCode method takes numbers that represent code units as parameters and returns the corresponding characters.

index.js
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 it's current implementation, the function would return a backtick character.

If a is supplied, this example returns z.

index.js
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 passed in character if it's a. This is entirely application dependent.

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