JavaScript Reference ยท String
String.prototype.charAt()
Reference for JavaScript String.prototype.charAt(): return the character at a given index, what happens out of range, and how it differs from at() and brackets.
The charAt() method returns a string containing the single UTF-16 code unit at a given zero-based index. If the index is outside the string, it returns an empty string rather than undefined.
It is one of the oldest string methods. Today, bracket notation (str[i]) or at() is used more often, but charAt() is still common in older code and is handy when you want a string result in every case.
"hello".charAt(1); // "e"
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.charAt(index)
| Name | Description |
|---|---|
index |
Zero-based position of the character to return. Converted to an integer (fractions are cut off); NaN and a missing argument become 0. Negative numbers are not counted from the end. |
Return value: a string of length 1 for a valid index, or an empty string "" if index is below 0 or not less than the string's length.
Exceptions: none.
Usage notes
- Never
undefined. The empty-string result lets you chain string methods safely, for examplestr.charAt(0).toUpperCase()works even on an empty string. - No negative indexing.
charAt(-1)returns"". Useat(-1)orcharAt(str.length - 1)for the last character. - Code units, not characters. For characters outside the Basic Multilingual Plane (most emoji),
charAt()returns one half of a surrogate pair. Iterate withfor...ofor the spread operator to get whole code points. - Same as brackets for valid indexes.
str.charAt(i)andstr[i]return the same value inside the string. They differ only out of range (""versusundefined). - Strings are read-only. You can read with
charAt()but not assign:str[0] = "x"silently does nothing (or throws in strict mode). - To compare characters,
str.charAt(i) === "a"works; for a numeric code usecharCodeAt(). - Generic.
String.prototype.charAt.call(value, i)converts the value to a string first, so it works on numbers:String.prototype.charAt.call(123, 1)returns"2".
Browser support
charAt() is a classic method available in every browser and Node.js version.