JavaScript Program to Print the First Letter of Each Word
Last Updated :
14 Mar, 2024
Printing the first letter of each word involves extracting the initial character from every word in a given string, typically accomplished by splitting the string into words and selecting the first character from each resulting word.
Examples of Printing the First Letter of Each Word
1. Using for loop with split method
In this method, we have used the split method that converts the string into an array of words using space as a delimiter then we use a for loop to iterate through each word in the array to get the first letter of each word.
Example: The below code uses the for loop with the split method to print the first letter of each word.
JavaScript
const PrintFirstLetter = (word) => {
let words = word.split(" ");
for (let i = 0; i < words.length; i++) {
let firstLetter = words[i][0];
console.log(firstLetter);
}
};
PrintFirstLetter("Geeks For Geeks");
2.Using forEach with Split method
In this method, we have used the split method that converts the string into an array of words using space as a delimiter then we are using forEach to iterate through each word in the array to get a first letter of each word.
Example: The below code implements split() and forEach() method to print the first letter of each word.
JavaScript
const PrintFirstLetter = (word) => {
let words = word.split(' ');
words.forEach((item) => {
let firstLetter = item[0];
console.log(firstLetter);
});
};
PrintFirstLetter("Geeks For Geeks");
3.Using split with map method
This approach splits the string into an array of words. Then, it uses the map method to iterate over each word and extract the first letter of each word.
Example: The below code implements split() and map() method to print the first letter of each word.
JavaScript
const string = "Geeks For Geeks";
const words = string.split(" ");
const firstLetters = words.map((word) => word[0]);
console.log(firstLetters.join("\n"));
4.Using Regular Expression with Map method
In this method, we have used the Regular expression to get the first letter of each word. In the regular expression \b is a word boundary anchor to match the beginning of a word, \w is a shorthand character class to match any word character (letter, digit, or underscore) and /g is a global flag for matching all occurrences in the entire string. map function is used to iterate through the matched first letters.
Example: The below code will explain the use of the Regular expression and map method to print the first letter of each word.
JavaScript
function PrintFirstLetter(word) {
let words = word.match(/\b\w/g);
words.forEach(firstLetter => {
console.log(firstLetter);
});
}
PrintFirstLetter("Geeks For Geeks");
Share your thoughts in the comments
Please Login to comment...