Sometimes, we want to get the next letter of the alphabet in JavaScript.
In this article, we’ll look at how to get the next letter of the alphabet in JavaScript.
Get the Next Letter of the Alphabet in JavaScript
To get the next letter of the alphabet in JavaScript, we can use the String.fromCharCode
static string method and the charCodeAt
string instance method.
For instance, we write:
const str = 'a'
const nextLetter = String.fromCharCode(str.charCodeAt(str.length - 1) + 1)
console.log(nextLetter)
to define the str
string.
Then we call str.charCodeAt(str.length - 1)
to get the character code of the last character of the string.
Next, we add 1 to the returned character code and call String.fromCharCode
to return the letter corresponding to that character code.
Finally, we assign the returned value to nextLetter
.
Therefore, we should see that nextLetter
is 'b'
from the console log.
Conclusion
To get the next letter of the alphabet in JavaScript, we can use the String.fromCharCode
static string method and the charCodeAt
string instance method.