JavaScript String charAt() Method

JavaScript String charAt() method is used to return a character at a specified index in a string. If the index is out of range (i.e., greater than or equal to the string’s length), the method returns an empty string.

Syntax

string.charAt(index)

Parameters

index(required): An integer representing the index of the character you want to return. If no index is provided, the default is 0.

Return value

Returns string representing the character (exactly one UTF-16 code unit) at the specified index.

Visual RepresentationVisual Representation of JavaScript String charAt() Method

Example 1: How to use String charAt() Method

let str = 'AppDividend';
res = str.charAt(5);

console.log(res);

Output

v

Example 2: Extracting the first letter of every string in the array

let friends = ['Rachel', 'Chandler', 'Ross', 'Phoebe', 'Joey'];

extractedString = friends.map(i => i.charAt(0));

console.log(extractedString);

Output

[ 'R', 'C', 'R', 'P', 'J' ]

In this example, the map() method is applied to the friends array. For each element in the array, the charAt(0)method is called, returning the first character of each string. Given the array [‘Rachel’, ‘Chandler’, ‘Ross’, ‘Phoebe’, ‘Joey’], the output will be [ ‘R’, ‘C’, ‘R’, ‘P’, ‘J’ ].

Example 3: Get the last Character of the StringVisual Representation of Get the last Character of the StringarAt() method

let str = 'AppDividend'; 
res = str.charAt(str.length-1); 
console.log(res);

Output

d

In the above example, The str.length-1 calculates the index of the last character in the string. Given the string ‘AppDividend‘  the last character is ‘d’. Therefore, the output is ‘d‘.

Example 4: Passing non-integer index value

Visual Representation of Passing no-integer index value to charAt()

let str = 'AppDividend';

data1 = str.charAt(7.3);

console.log("Character at index 7.3 is " + data1);

data2 = str.charAt(2.6);

console.log("Character at index 2.6 is " + data2);

Output

Character at index 7.3 is d
Character at index 2.6 is p

Example 5: Without passing a parameter Visual Representation of Without passing a parameter in the charAt() method

If you don’t pass any parameter to the charAt() function, then it will return the first character of a string.

let str = 'AppDividend'; 
res = str.charAt(); 
console.log(res);

Output

A

Example 6: When the index value is out of range Visual Representation of When the index value is out of range in the charAt() method

let str = 'AppDividend';
res = str.charAt(23);
console.log("Character at index 23 is: " + res);

Output

Character at index 23 is: 

In the above example, it returns an empty string(‘ ‘) because the index is out of range.

Browser compatibility

  • Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Opera 3 and above
  • Safari 1 and above

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.