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.
"A".codePointAt(0); // 65
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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 index1, andBis at index3, because the emoji occupies indexes1and2. - Landing in the middle of a pair returns only the second half (a lone low surrogate, in the range
0xDC00to0xDFFF). In the first examplecodePointAt(2)is56832, 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 givesundefined, not a count from the end. - Iterate with
for...of(or spread orArray.from) to visit whole code points, then callcodePointAt(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.