The String charCodeAt() method

By

Learn how the JavaScript charCodeAt() method returns the Unicode 16-bit integer code for the character at a given index in a string, unlike charAt().

~~~

charCodeAt() returns the character code at the index you pass. It’s similar to charAt(), except it returns a number instead of the character itself: the UTF-16 integer representing that character.

'Flavio'.charCodeAt(0) //70
'Flavio'.charCodeAt(1) //108
'Flavio'.charCodeAt(2) //97

70 is the code for F, 108 is the code for l, and 97 is the code for a.

The number is always in the range 0 to 65535. JavaScript strings are stored as sequences of 16-bit units, and charCodeAt() gives you one of those units.

When would you use it?

You reach for character codes when you need to work with characters as numbers.

For example, you can check if a character is an uppercase letter. Uppercase letters go from code 65 (A) to code 90 (Z):

const code = 'F'.charCodeAt(0)
code >= 65 && code <= 90 //true

You can also go the other way with String.fromCharCode(), which builds a string from codes:

String.fromCharCode(70, 108, 97) //'Fla'

What if the index doesn’t exist?

If you pass an index that’s out of range, you get NaN back, not an error:

'Flavio'.charCodeAt(10) //NaN

Getting the hexadecimal code

Calling toString(16) on the result will return the hexadecimal number, which you can lookup in Unicode tables like this:

'Flavio'.charCodeAt(0).toString(16) //'46'

Be careful with emoji

Some characters don’t fit in a single 16-bit unit. Emoji are the common case: they take two units, called a surrogate pair.

charCodeAt() only sees one unit at a time, so it gives you half the pair:

'🐶'.charCodeAt(0) //55357
'🐶'.charCodeAt(1) //56374

Neither of those numbers identifies the dog emoji. If you need the real code of the full character, use codePointAt() instead:

'🐶'.codePointAt(0) //128054

For plain ASCII text the two methods return the same values, so this only bites you when emoji or other rare characters show up in your strings.

~~~

Related posts about js: