How to convert a char to its keycode?

前端 未结 5 1365
闹比i
闹比i 2020-12-09 14:26

How can I convert a character to its respective keycode?

For example:

  • a to 65
  • b to 66
5条回答
  •  一生所求
    2020-12-09 15:19

    I was searching for this when I stumbled upon this question. I do not think the marked answer is the right answer. For simple letters, A-Za-z, I use the following:

    function getKeyCode(char) {
      var keyCode = char.charCodeAt(0);
      if(keyCode > 90) {  // 90 is keyCode for 'z'
        return keyCode - 32;
      }
      return keyCode;
    }
    

    Please note that this is meant to work for characters A-Z and a-z only.

提交回复
热议问题