JavaScript String charAt()
Examples
Get the first character in a string:
let text = "HELLO WORLD";
let letter = text.charAt(0);
Try it Yourself »
Get the second character in a string:
let text = "HELLO WORLD";
let letter = text.charAt(1);
Try it Yourself »
Get the last character in a string:
let text = "HELLO WORLD";
let letter = text.charAt(text.length-1);
Try it Yourself »
More examples below.
Description
The charAt()
method returns the character at a specified index (position) in a string.
The index of the first character is 0, the second 1, ...
See Also:
Syntax
string.charAt(index)
Parameters
Parameter | Description |
index | Optional. The index (position) of the character. Default = 0. |
Return Value
Type | Description |
String | The character at the specified index. Empty string ("") if the index is out of range. |
More Examples
Index out of range returns empty string:
let text = "HELLO WORLD";
let letter = text.charAt(15);
Try it Yourself »
Default index is 0:
let text = "HELLO WORLD";
let letter = text.charAt();
Try it Yourself »
Invalid index converts to 0:
let text = "HELLO WORLD";
let letter = text.charAt(3.14);
Try it Yourself »
Browser Support
charAt()
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |