How to Detect a Letter Key on Key Events with Javascript
What to do instead of using the deprecated keyCode value without dealing with regex.
Don’t use e.keyCode
If you’re here, I assume it’s because you’re trying to isolate functionality to letter presses only. In an attempt to do so, you might have heard about keyCodes and used something like:
if (e.keyCode ≥ 65 && e.keyCode ≤ 90){...}
In doing so, you might have come across a deprecation warning (assuming you’re using Visual Studio Code):
I won’t go into details, as you can learn all about these things on MDN.
The Simple Solution (No Regex Required)
Letter keys have their unique formatting value in their code property. The letter d, for instance, has a code property with a value of KeyD. So all you need to do is give the condition that only if the event code matches that format, should the program continue.
To do so, just give the condition using string template literals to make it easy to match the letter that was pressed:
if (e.code === `Key${e.key.toUpperCase()}`){
console.log(`You pressed ${e.key}`);
}
Or, even better, use it as a guard clause within the event handler callback:
if (e.code !== `Key${e.key.toUpperCase()}`) return;
This way, any key you press will have to match that format in order to move forward. And you didn’t need to use regex, as some solutions from a few years ago may have needed.