String.charAt()
The String.charAt()
method returns a new string at the specified index argument.
Syntax
str.charAt(0); // returns first letter of string
Quick Example
var str = 'CodeSnippet';
var firstLetter = str.charAt(0);
console.log(firstLetter); // returns 'C'
Try this the code snippet in your browser console.
Real World Example 🔤
Let's suppose you had a list of customers and you wanted to organize them separately into alphabetical lists. We can use the .charAt()
method to look at the first character of each customer name and then push them to a particular array.
// Array of customers
var customers = ['Bob', 'Chris', 'Alice', 'Aaron', 'Bill', 'Brian', 'Caitlin', 'Andrea', 'Bailey'];
// Initialize arrays where we will be adding customers
// based on first letter of name
var A = [];
var B = [];
var C = [];
// Loop through list of customers
for (var i in customers) {
// if first letter of customer name starts with 'A'
if (customers[i].charAt(0) === 'A') {
// add customer to 'A' list
A.push(customers[i]);
// if first letter of customer name starts with 'B'
} if (customers[i].charAt(0) === 'B') {
// add customer to 'B' list
B.push(customers[i]);
// if first letter of customer name starts with C
} if (customers[i].charAt(0) === 'C') {
// add customer to 'C' list
C.push(customers[i]);
}
}
// Log the different lists
console.log('A:', A);
console.log('B:', B);
console.log('C:', C);
Try this the code snippet in your browser console.
Wrapping Up 📝
The String.charAt()
method is a helpful way to check which characted exists within a string at a specified index.
Stay Tuned 📺
If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at tim@timwheeler.com
. If you're enjoying my posts, please subscribe below! 👇