Javascript String charAt() is an inbuilt method that returns the new string consisting of a single UTF-16 code unit located at a specified offset into a string. The charAt() method returns a character at the specified index in the string. The index of a first character is 0; the second character is 1, and so on.
String_Object.CharAt(index)
String_Object
: Please select the valid String Object.Index
: Provide the index position of the desired character.ChartAt Function in Javascript returns the Character from String_Object at specified Index_Position. If we specify the Index position out of range, ChartAt Function returns an empty string.
let str = 'Morioh';
let res = str.charAt(5);
console.log(res);
So, it will return the character at position 5, and the string’s index is starting from 0. So it should return 0.
Output
Extract the first letter of every string in the array
We can extract the first letter of an array by the following code.
// app.js
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 need to only get only the first character from each item. So first we map through each item and get the first character and add that characters into an array and return it. Since the map method is a pure function, it will return a new array.
Output
Finally, Javascript String charAt() function example is over.
Thanks for reading !
#js #javascript