Skip to main content
Version: 3.27.2

String.prototype.charCodeAt()

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit. If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than 0xFFFF) then the code unit returned will be the first part of a surrogate pair for the code point. If you want the entire code point value, use codePointAt().

Syntax

charCodeAt(index)

Parameters

  • index
    • : An integer greater than or equal to 0 and less than the length of the string. If index is not a number, it defaults to 0.

Return value

A number representing the UTF-16 code unit value of the character at the given index. If index is out of range, charCodeAt() returns NaN.

Description

Unicode code points range from 0 to 1114111 (0x10FFFF). The first 128 Unicode code points are a direct match of the ASCII character encoding. (For information on Unicode, see UTF-16 characters, Unicode codepoints, and grapheme clusters.)

Note: charCodeAt() will always return a value that is less than 65536. This is because the higher code points are represented by a pair of (lower valued) "surrogate" pseudo-characters which are used to comprise the real character.

Because of this, in order to examine (or reproduce) the full character for individual character values of 65536 or greater, for such characters, it is necessary to retrieve not only charCodeAt(i), but also charCodeAt(i+1) (as if manipulating a string with two letters), or to use codePointAt(i) instead. See examples 2 and 3 (below).

charCodeAt() returns NaN if the given index is less than 0, or if it is equal to or greater than the length of the string.

Backward compatibility: In historic versions (like JavaScript 1.2) the charCodeAt() method returns a number indicating the ISO-Latin-1 codeset value of the character at the given index. The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct match of the ASCII character set.