Open In App

JavaScript String charAt() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The JavaScript String charAt() method retrieves the character at a specified index in a string. The index is passed as an argument to the method, and it returns the character at that position.

Note: JavaScript uses zero-based indexing, meaning the first character is at index 0, the second at index 1, and so on.

Syntax:

character = str.charAt(index);

Parameters:

  • index: The range of this index is between 0 and length – 1. If no index is specified then the first character of the string is returned as 0 is the default index used for this function. 

Return Value: Returns a single character located at the index specified as the argument to the function. If the index is out of range, then this function returns an empty string.

JavaScript String charAt() Method Examples

Example 1: Retrieving Characters at Specific Indices using JavaScript String charAt() Method

The charAt() method in JavaScript is used to find and retrieve characters at specified indices in a string. In this example, it retrieves characters at indices 0 and 4 from the given string.

JavaScript
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();

Output
J
S

Example 2: Retrieving Character at Out-of-Bounds Index with JavaScript String charAt() Method

The charAt() method in JavaScript returns an empty string when the specified index is out of bounds (greater than or equal to the string’s length). In this example, it attempts to access the character at index 50, which is beyond the length of the string. As a result, an empty string is returned.

Javascript
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();

Output

We have a complete list of JavaScript string methods, to check those please go through this Javascript String Complete reference article.

Supported Browser: 

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.


Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads