Convert a character to its ASCII code in JavaScript
Codemia Knowledge Hub ·
Use charCodeAt(index) on a string: 'Hello'.charCodeAt(0) returns 72, the ASCII code of H. Strictly, it returns the UTF-16 code unit at that position, which equals the ASCII value for English letters, digits and basic punctuation.
ASCII (American Standard Code for Information Interchange) assigns a number to each English letter, plus control characters and special symbols, which is handy when you need to analyze or manipulate characters by value.
Using charCodeAt()
charCodeAt() is a string method that returns an integer for the character at the given position.
Syntax:
- string: the string containing the character.
- index: the position of the character. The first character is at index 0.
Example:
The ASCII code of 'H' is 72.
Characters outside ASCII: UTF-16 and codePointAt()
charCodeAt() returns a UTF-16 code unit. For characters in the Basic Multilingual Plane (BMP) that also exist in ASCII, that is the same as the ASCII value.
For characters outside the BMP, such as emoji, charCodeAt() returns only the leading surrogate of the surrogate pair, which does not correspond to any ASCII value. Use codePointAt() to get the full code point when working with Unicode text.
ASCII codes for English letters
| Character | ASCII Code |
| A | 65 |
| B | 66 |
| C | 67 |
| ... | ... |
| Z | 90 |
| a | 97 |
| b | 98 |
| c | 99 |
| ... | ... |
| z | 122 |
Getting codes for every character in a string
Loop through the string with a for loop, or with higher-order array methods if you split it into an array first:
charCodeAt() is enough for data validation, encoding or other work on ASCII characters; switch to codePointAt() for full Unicode support in international applications.
Related reading
- Convert HTML to Plain Text in Swift
- Convert JavaScript String to be all lowercase
- Convert JS date time to MySQL datetime
- Convert JS object to JSON string
- Convert JSON to Map
- Convert MySql DateTime stamp into JavaScript's Date format
- Converting JS object to ArrayBuffer to transfer to/from web worker equals bottleneck
- Copy array items into another array
System design interview problems on this topic
- Design Google Doc: solution and walkthrough
- Design Facebook Messenger: solution and walkthrough
- Design Typeahead Suggestion: solution and walkthrough
- Design an Online Presence Indicator Service: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.