Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.codePointAt()

Reference for JavaScript String.prototype.codePointAt(): read the full Unicode code point at an index, including emoji, and how it differs from charCodeAt().

The codePointAt() method returns the Unicode code point that starts at a given index in a string. A code point is the number Unicode assigns to a character, such as 65 for A or 128512 for the grinning-face emoji.

JavaScript strings are sequences of 16-bit UTF-16 code units. Characters outside the Basic Multilingual Plane, such as most emoji, take two units (a surrogate pair). codePointAt() reads both units and combines them into one number, which charCodeAt() does not.

JavaScript
"A".codePointAt(0); // 65

Try it

JS Code units versus code points

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Listing code points in hex

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string.codePointAt(index)
Name Description
index Zero-based position of a UTF-16 code unit. It is converted to an integer; a missing value counts as 0.

Return value: the code point (an integer from 0 to 0x10FFFF) that starts at index, or undefined if index is negative or not smaller than the string length.

Exceptions: none.

Usage notes

  • The index counts code units, not characters. In "A๐Ÿ˜€B" the emoji sits at index 1, and B is at index 3, because the emoji occupies indexes 1 and 2.
  • Landing in the middle of a pair returns only the second half (a lone low surrogate, in the range 0xDC00 to 0xDFFF). In the first example codePointAt(2) is 56832, which is not a real character.
  • Lone surrogates are returned as they are. A string that contains one is not well formed; see isWellFormed().
  • No negative indexes. Unlike at(), a negative index gives undefined, not a count from the end.
  • Iterate with for...of (or spread or Array.from) to visit whole code points, then call codePointAt(0) on each piece, as in the second example.
  • A code point is not always one visible character. An emoji with a skin tone or a letter with a combining accent is several code points. See strings and Unicode.
  • The inverse is String.fromCodePoint().
  • Compared with charCodeAt(): for characters in the Basic Multilingual Plane the two return the same number. For anything else, charCodeAt() returns only one surrogate.

Browser support

codePointAt() is part of ES2015 and works in all current browsers.