JavaScript String charAt() Method

JavaScript String charAt() is a built-in method that returns the character at a specified index within 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

The index parameter is required. It is an integer representing the index of the character you want to return.

Example

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

console.log(res);

It will return the character to position 5, and the string’s index starts from 0. So it should return 0.

Output

Javascript String CharAt Example | String.prototype.charAt() Tutorial

Extracting the first letter of every string in the array

We can extract the first letter of an array by the following code.

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

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

console.log(extractedString);

We have defined one array full of strings. Now, we only need to get the first character from each item.

We map through each element, get the first character, add that character to an array, and return it. Since the map method is a pure function, it will return a new array.

Output

String.prototype.charAt() Tutorial

Displaying the characters at different locations in the string

We can show all the characters like this.

let OString = 'appdividend';

console.log("The character at index 0 is '" + OString.charAt(0) + "'");
console.log("The character at index 1 is '" + OString.charAt(1) + "'");
console.log("The character at index 2 is '" + OString.charAt(2) + "'");
console.log("The character at index 3 is '" + OString.charAt(3) + "'");
console.log("The character at index 4 is '" + OString.charAt(4) + "'");
console.log("The character at index 5 is '" + OString.charAt(5) + "'");
console.log("The character at index 6 is '" + OString.charAt(6) + "'");
console.log("The character at index 7 is '" + OString.charAt(7) + "'");
console.log("The character at index 8 is '" + OString.charAt(8) + "'");
console.log("The character at index 9 is '" + OString.charAt(9) + "'");
console.log("The character at index 10 is '" + OString.charAt(10) + "'");

Output

Extract the first letter of every string in the array

That’s it.

Leave a Comment

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