In my React/Javascript app, I am listening for KeyboardEvents. The documentation for the key property is quite clear on how to get the pressed key value:
Its value is determined as follows:
- If the pressed key has a printed representation, the returned value is a non-empty Unicode character string containing the printable representation of the key.
- If the pressed key is a Space key, the returned value is a single space
- If the pressed key is a control or special character, the returned value is one of the pre-defined key values.
I want to test that the pressed key has a printed representation or is a Space. i.e. it is NOT one of the pre-defined key values.
I could not find a hasPrintedRepresentation property. Should I write my own hasPrintedRepresentation() that tests and excludes each one of those 400-or-so pre-defined key values before returning true? I could not find a library that already does this grunt work. Did I miss something? Thank you!
You could use the
keyproperty of the KeyboardEvent object to get the pressed key value.You could use the
Object.hasOwn()method in JavaScript to check if thekeyproperty of the KeyboardEvent object has a printed representation or is a Space. TheObject.hasOwn()method returnstrueif the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returnsfalse.Here's an example of how you could use the
Object.hasOwn()method to test if the pressed key has a printed representation or is a Space: