I am currently working on a Javascript & HTML project where I am receiving an input from a user. As I need to log key presses at all times I have opted against using a text box & submit button, but have rather opted for having a script running in the background which checks if & which key is pressed (Shown Below).
document.addEventListener("keydown", (event) => {
var key = event.key;
});
The issue I have run into is that the keydown event returns all forms of key press including ones like ‘Shift’ or ‘Backspace’. I want to disregard the non-charcter key presses. I have a piece of code which does what I want using RegEx but I was wondering if there were any better solutions.
My current solution is as follows:
document.addEventListener("keydown", (event) => {
var key = event.key;
if (key.match(/^[ -~]+$/) && key.length == 1) {
alert(key);
}
});
I am new to Javascript and this is my first experience using RegEx so I assumed from this table that [ -~]
checks the key pressed against the ‘Space’ character to the tilde.
This seems to work but I was wondering whether there are any issues I could run into with this and/or if there is a better potential solution.
Thanks in advance for your help!
2
Answers
You can do this by editing your code to strictly check for letters.
The conditions
!event.ctrlKey
,!event.altKey
, and!event.metaKey
block the keys you do not want. From my testing, it works on the most updated Chrome and Firefox.You write "I want to disregard the non-character key presses", but then realise that there thousands of different characters that can be typed on keyboards around the world — the table you refer to just lists a tiny subset of those (the ASCII set). For instance, my keyboard has a key for "µ", which your regex will not match. Also, it has a "^" key that will not trigger anything until another key is typed with which it is combined, like "î", which will be the
key
property of the event object.You could just count the number of characters in the
key
property, and if there is just one, you can conclude it is a printable character. Just to be prudent, there might be keyboards that have keys for characters that need two code units, and thenlength
would give 2 instead of 1. So to be really sure you’d use[...event.key].length
instead, which would still give 1 in that case.