67

How to convert keycode to character using javascript

var key_code = 65;

result should be

character = "a";
danronmoon
  • 3,814
  • 5
  • 34
  • 56
faressoft
  • 19,053
  • 44
  • 104
  • 146
  • 1
    Worth remembering that [charCode sniffing is bad for your health](http://unixpapa.com/js/key.html) (and by health, I think I mean sanity). [See also here](http://stackoverflow.com/a/5829387/1028230). Getting better since this question was asked, but still a nontrivial pain. – ruffin Sep 29 '15 at 13:46
  • @ruffin This is the best answer! – Míng Aug 23 '21 at 15:05

2 Answers2

132

String.fromCharCode() is what you want:

The fromCharCode() method converts Unicode values to characters.

Syntax

String.fromCharCode(n1, n2, ..., nX)
Community
  • 1
  • 1
Skilldrick
  • 69,215
  • 34
  • 177
  • 229
  • 5
    Notice that String.fromCharCode(65) == 'A', to get 'a' a call to .toLowerCase() is needed. – Arrix Oct 20 '10 at 12:40
  • 64
    Only if you've got the "key code" from a `keypress` event. In `keyup` and `keydown` events, the `keyCode` property has nothing to do with characters. – Tim Down Oct 20 '10 at 13:12
  • keyCode property from keydown event is the right combination to use with String.fromCharCode(). It works for me not the charCode. – Otuk Aug 28 '12 at 17:06
  • 4
    @Arrix: yes, so how do you know if you need to call toLowerCase()? You can't just look at event.shiftKey, because this will fail for keys like "!" – Michael Apr 21 '13 at 21:30
  • 1
    @Michael, I would suggest to always use .toLowerCase() if searching for specific letter (as in the example String.fromCharCode(65) == 'a'). There is no error thrown when trying to convert a lower case letter to lower case. – einord Aug 11 '14 at 21:28
  • Readers beware: this approach completely fails if you're working with function keys (ie. 'F12'). The best approach I found is to just give in and use `event.key` instead of `event.keyCode` (and add a special case for each keyboard layout you need to support). It's less robust but that's JS for you. – Tenders McChiken Feb 23 '21 at 14:16
12

As seen here:

String.fromCharCode((96 <= key && key <= 105) ? key-48 : key)
Community
  • 1
  • 1
garsax
  • 163
  • 1
  • 5
  • Could you elaborate what this code does or checks? – kontur Sep 18 '18 at 10:18
  • This code maps Windows numpad keycodes for numpad 0 to numpad 9 (96 through 105) to the character codes 48 through 57, allowing the method to convert them back to their underlying values "0" to "9". This has no effect on Mac, as the numpad numbers already map to 48 to 57. – remo Mar 12 '19 at 14:32