ArticleZip > Get First Letter Of Each Word In A String In Javascript

Get First Letter Of Each Word In A String In Javascript

Getting the first letter of each word in a string is a handy task in JavaScript that can be useful in various programming scenarios. Whether you are working on a text processing feature or need to manipulate data within a string, extracting the initial character of each word can help you achieve your goals more effectively. In this guide, we will dive into how you can accomplish this task using JavaScript.

To get started, you can use JavaScript's built-in methods to achieve this. One approach is to split the input string into an array of words and then map over each word to extract the first letter. Here's a step-by-step breakdown of how you can implement this:

Javascript

function getFirstLetters(str) {
  // Split the input string into an array of words
  const words = str.split(' ');

  // Map over each word and extract the first letter
  const firstLetters = words.map(word => word.charAt(0));

  // Return the resulting array of first letters
  return firstLetters;
}

// Test the function with a sample input
const inputString = 'Hello World';
const result = getFirstLetters(inputString);

console.log(result); // Output: ['H', 'W']

In the code snippet above, the `getFirstLetters` function takes a string as input, splits it into an array of words using the space as a delimiter, and then maps over each word to extract the first character using the `charAt(0)` method. Finally, it returns an array containing the first letters of each word in the original string.

Furthermore, you can enhance this functionality by ensuring that the output always contains uppercase letters for consistency. You can achieve this by modifying the code as shown below:

Javascript

function getFirstLetters(str) {
  const words = str.split(' ');
  const firstLetters = words.map(word => word.charAt(0).toUpperCase());
  return firstLetters;
}

// Test the function with a lowercase input string
const inputString = 'lorem ipsum dolor sit amet';
const result = getFirstLetters(inputString);

console.log(result); // Output: ['L', 'I', 'D', 'S', 'A']

In this version of the function, we use the `toUpperCase` method to ensure that each first letter is transformed into uppercase before adding it to the result array. This way, you can maintain a consistent format for the output regardless of the case of the input string.

By following these steps and customizing the code to suit your specific requirements, you can easily extract the first letter of each word in a string using JavaScript. This simple technique can be a valuable tool in your programming toolkit, allowing you to manipulate text data efficiently in your projects.