I'm making a letter guessing game and I want the onkeyup to only accept alphabet keys.
document.onkeyup = function (event) {
var userGuess = event.key;
}
I'm making a letter guessing game and I want the onkeyup to only accept alphabet keys.
document.onkeyup = function (event) {
var userGuess = event.key;
}
Another option is to get the keycode from the which-property of the event and translate it to a char. Then you can test the char with regex.
document.addEventListener('keyup', function (event) {
let char = String.fromCharCode(event.which);
if (/[a-z]/i.test(char)) {
// Do something
console.log(char);
}
});
Press any key!
Check the ASCII code:
if (event.keyCode >= 65 && event.keyCode <= 90) {
console.log("input was a-z");
}
Since keyCode is being deprecated, a slightly more modern approach could be something like this...
window.addEventListener('keyup', event => {
if (event.key >= 'a' && event.key <= 'z') {
// do something
}
}