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 Representation
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 String
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
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
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
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
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.