Open In App
Related Articles

JavaScript String charAt() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

The charAt() method in JavaScript is used to retrieve the character at a specified index within 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.

Example 1: Below is an example of the String charAt() Method.

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: In this example, the function charAt() finds the character at index 9 and returns it. 

JavaScript

function func() {
 
    // Original string
    let str = 'JavaScript is object oriented language';
 
    // Finding the character at given index
    let value = str.charAt(9);
    console.log(value);
}
func();

                    

Output
t

Example 3: In this example, the function charAt() finds the character at index 50. Since the index is out of bounds for the given string therefore the function returns “”an empty string. 

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

Example 4: In this example we are using a variable as the index

Javascript

let str = 'Geeksforgeeks!';
let index = 4;
 
console.log(str.charAt(index));

                    

Output
s

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

Supported Browser: 

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

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 : 28 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads