How to convert character to/from keycode in javascript?

This tutorial shows 2 ways to convert keycode to/from the character in JavaScript.

One way to charCodeAt() function converts a character to a keycode character, and the fromCharCode() function converts the Unicode keycode to the character.

Key codes for letters are unique numbers for any character including Unicode characters.

Keycodes and characters are

  • 97-122 for a-z characters
  • 65-90 for A-Z characters.
  • 48-57 for 0-9

The above functions only work with single characters, not strings, that contain more than one character.

You can check my other post on Javascript check substring exists in a String

How to Convert character to keycode in javascript

The charCodeAt() method returns the keycode for a character.

charCodeAt()returns the number for a given character based on the following ranges

  • 97-122 for a-z characters
  • 65-90 for A-Z characters.
  • 48-57 for 0-9
console.log("a".charCodeAt(0)); // 97
console.log("z".charCodeAt(0)); // 122
console.log("A".charCodeAt(0)); // 65
console.log("Z".charCodeAt(0)); //90

How to get characters for a given keycode in JavaScript?

String.fromCharCode() takes one or many keycodes and returns characters.

Syntax:

String.fromCharCode(arg1,arg2...)

Arguments are one or more keycode characters. Returns Character

Here is an example

console.log(String.fromCharCode(97)); //a
console.log(String.fromCharCode(122)); //z
console.log(String.fromCharCode(65, 90)); //AZ

Conclusion

In summary, Learned ways to convert characters to/from keycodes in javascript with examples. These two methods convert based on the Unicode Character Set, These do not work with nonascii characters.