I see examples where people, in order to check if e.key
is a printable character, check key.length
(where 1
means a printable char). Other people also check for !e.ctrlKey && !e.metaKey && !e.altKey
(modifier key).
For what I can see doing some tests, only the first is required. So, Is the second check just excessive zeal?
document.addEventListener('keyup', (e) => {
const isPrintableChar = e.key.length === 1;
const noModifier = !e.ctrlKey && !e.metaKey && !e.altKey;
// Just check the length
if (isPrintableChar) {
console.log('printable');
}
// Check both length and if it's a modifier
if (isPrintableChar && noModifier) {
console.log('printable+');
}
});