Just an important note: the accepted answer above will not work correctly for keyCode >= 144, i.e. period, comma, dash, etc. For those you should use a more general algorithm:
let chrCode = keyCode - 48 * Math.floor(keyCode / 48);
let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);
If you're curious as to why, this is apparently necessary because of the behavior of the built-in JS function String.fromCharCode()
. For values of keyCode <= 96
it seems to map using the function:
chrCode = keyCode - 48 * Math.floor(keyCode / 48)
For values of keyCode > 96
it seems to map using the function:
chrCode = keyCode
If this seems like odd behavior then well..I agree. Sadly enough, it would be very far from the weirdest thing I've seen in the JS core.
document.onkeydown = function(e) {_x000D_
let keyCode = e.keyCode;_x000D_
let chrCode = keyCode - 48 * Math.floor(keyCode / 48);_x000D_
let chr = String.fromCharCode((96 <= keyCode) ? chrCode: keyCode);_x000D_
console.log(chr);_x000D_
};
_x000D_
<input type="text" placeholder="Focus and Type"/>
_x000D_