JavaScript Reference ยท String
String.prototype.charCodeAt()
Reference for JavaScript String.prototype.charCodeAt(): get the UTF-16 code unit number at an index, handle NaN, and why emoji need codePointAt() instead.
The charCodeAt() method returns the numeric value of the UTF-16 code unit at a given index. The result is an integer between 0 and 65535. For ordinary letters, digits and punctuation this equals the character's Unicode (and ASCII) number: "A".charCodeAt(0) is 65.
If the index is outside the string, the result is NaN. For characters beyond U+FFFF, such as emoji, charCodeAt() sees only one half of a surrogate pair; use codePointAt() for the full code point.
"A".charCodeAt(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.charCodeAt(index)
| Name | Description |
|---|---|
index |
Zero-based position. It is converted to an integer (fractions are cut off); NaN and a missing argument become 0. |
Return value: an integer from 0 to 65535, the UTF-16 code unit at index, or NaN if index is negative or not less than the string's length.
Exceptions: none.
Usage notes
NaN, notundefined. Out-of-range reads giveNaN, which is never equal to itself. Test withNumber.isNaN(code), or compare the index withlengthfirst.- Code units, not code points. For a character above
U+FFFF, you get a high surrogate (0xD800to0xDBFF) at the first index and a low surrogate (0xDC00to0xDFFF) at the next.codePointAt()combines them into one number. - Not always ASCII. Values above
127are non-ASCII characters; values above255do not fit in a single byte. - Inverse operation.
String.fromCharCode()converts the numbers back into characters. - Not for sorting by language. Code unit order is not alphabetical order in most languages; use
localeCompare()orIntl.Collator. - Not a byte count. The number of code units says nothing about UTF-8 byte length; encode with
TextEncoderto count bytes. - Uses: simple hashes and checksums, character-class checks, and converting letters to numbers (
ch.charCodeAt(0) - 97foratoz).
Browser support
charCodeAt() is a classic method that works in every browser and Node.js version.