How to Access Character in String in JavaScript: Simple Guide
In JavaScript, you can access a character in a string using
string[index] or the string.charAt(index) method, where index is the position starting from 0. Both return the character at that position, but bracket notation returns undefined if out of range, while charAt() returns an empty string.Syntax
You can get a character from a string in two main ways:
- Bracket notation:
string[index]whereindexis the zero-based position of the character. - charAt() method:
string.charAt(index)which returns the character at the given position.
Index starts at 0, so the first character is at position 0.
javascript
const str = "hello"; const char1 = str[1]; const char2 = str.charAt(1); console.log(char1); console.log(char2);
Output
e
e
Example
This example shows how to access characters at different positions in a string using both bracket notation and charAt(). It also shows what happens if you try to access an index outside the string length.
javascript
const message = "JavaScript"; console.log(message[0]); // J console.log(message.charAt(4)); // S console.log(message[10]); // undefined console.log(message.charAt(10)); // "" (empty string)
Output
J
S
undefined
Common Pitfalls
Common mistakes include:
- Using 1-based index instead of 0-based (first character is at index 0).
- Accessing an index outside the string length, which returns
undefinedwith bracket notation or an empty string withcharAt(). - Trying to use bracket notation on
nullorundefinedvalues, which causes errors.
Always check the string length before accessing characters to avoid unexpected results.
javascript
const text = "abc"; // Wrong: 1-based index console.log(text[1]); // b (correct), but if you expect 'a', it's wrong // Out of range console.log(text[5]); // undefined console.log(text.charAt(5)); // "" (empty string)
Output
b
undefined
Quick Reference
| Method | Syntax | Returns | Out of Range Behavior |
|---|---|---|---|
| Bracket notation | string[index] | Character at index or undefined | undefined |
| charAt() method | string.charAt(index) | Character at index or empty string | Empty string |
Key Takeaways
Use zero-based index to access characters in a string.
Bracket notation and charAt() both get characters but differ on out-of-range behavior.
Bracket notation returns undefined if index is invalid; charAt() returns an empty string.
Always check string length before accessing characters to avoid errors.
charAt() is safer if you want a string result even for invalid indexes.