JavaScript
Coding
ASCII Code
Character Conversion
Programming

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:

javascript
string.charCodeAt(index)
  • string: the string containing the character.
  • index: the position of the character. The first character is at index 0.

Example:

javascript
let str = 'Hello';
let asciiCode = str.charCodeAt(0);
console.log(asciiCode); // Outputs: 72

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

CharacterASCII Code
A65
B66
C67
......
Z90
a97
b98
c99
......
z122

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:

javascript
1let text = "Hello, World!";
2let asciiCodes = [];
3
4for (let i = 0; i < text.length; i++) {
5    asciiCodes.push(text.charCodeAt(i));
6}
7
8console.log(asciiCodes);
9// Outputs: [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]

charCodeAt() is enough for data validation, encoding or other work on ASCII characters; switch to codePointAt() for full Unicode support in international applications.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Data 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.

Practice algorithms