A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-string-charat-method/ below:

JavaScript String charAt() Method - GeeksforGeeks

JavaScript String charAt() Method

Last Updated : 12 Jul, 2024

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: 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.

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

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

""
Supported Browsers: 

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4