JavaScript and ASCII
handling user input based on keystrokes or any single-character input
ASCII (American Standard Code for Information Interchange) refers to a way to encode a character into a number.
For example, the uppercase A
corresponds with an ASCII code of 65, while the lowercase a
corresponds to 97.
ASCII has 128 characters in all covering the letters A-Z (and a-z), numbers (0-9), some symbols (!, @, #, ...) and some other characters for line breaks and tab indents.
ASCII use case
ASCII's 128 characters makes it a limited set, which makes newer systems like Unicode better for storing all the characters of all the world's langauges. However, we still use ASCII for user input from a keyboard (especially an English language one, which is the most widely used).
When a user presses a button on a keyboard, the keyboard translates the "button press" into an ASCII value (you can try this single-page add call keycode.info to learn more!)
Using ASCII values with JavaScript allows programming keystroke shortcuts for a website.
Finding the ASCII value of a character with charCodeAt()
charCodeAt()
We can lookup the ASCII value of a character in a JavaScript String
with charCodeAt()
:
Finding a human-readable character based on a given ASCII value with fromCharCode()
fromCharCode()
The opposite of charCodeAt()
is fromCharCode(),
which takes an ASCII value and converts it into a String
character:
Once again, the website keycode.info allows you to check your ASCII values!
Last updated