The charAt() method in JavaScript is used to get a character from a string at a specific position. It helps you access individual characters easily using an index value.
- It takes an index number as an argument and returns the character at that position.
- JavaScript follows zero-based indexing (first character is at index 0).
- If the index is out of range, it returns an empty string.
let text = "Hello";
let result = text.charAt(1);
console.log(result);
Syntax:
character = str.charAt(index);Parameters:
The charAt() method accepts a single parameter called index. This index determines which character from the string will be returned.
- The index must be between 0 and string.length - 1.
- If no index is provided, it uses 0 by default.
- By default, it returns the first character of the string.
Return Value:
The charAt() method returns a value based on the index you provide. It gives you the character found at that specific position in the string.
- Returns the character located at the given index.
- If the index is valid, a single character is returned.
- If the index is out of range, it returns an empty string ("").
Example : Retrieving Characters at Specific Indices using JavaScript String charAt() Method.
The charAt() method is used to retrieve a character from a string at a specific index.
- Indexing starts from 0
- Returns a single character
- Returns an empty string if the index is invalid
- Useful for accessing individual characters in a string
function func() {
// Original string
let str = 'JavaScript is object oriented language';
// Finding the character at given index
let value = str.charAt(0);
let value1 = str.charAt(4);
console.log(value);
console.log(value1);
}
func();
Example : Retrieving Character at Out-of-Bounds Index with JavaScript String charAt() Method
The charAt() method returns an empty string when the given index is outside the string length.
- Index must be less than the string length
- Out-of-bounds indices return "" (empty string)
- No error is thrown for invalid indices
- Example: accessing index 50 in a shorter string returns an empty string
function func() {
// Original string
let str = 'JavaScript is object oriented language';
// Finding the character at given index
let value = str.charAt(50);
console.log(value);
}
func();