1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

Get All the First Letters of Words in a String

ReadTime: 5 minutes

In this blogpost, we’ll see how to get the first characters from all the words in a Javascript string, using: split, map, and join; regular expressions; reduce; and array destructuring. We’ll also cover some common errors and a practice problem.


Method 1: Using .split(), .map(), and .join()

This classic function trio can be used to:

  • break the string into an array of words,
  • then map each word to its first letter, and
  • then join them back together. Here’s the breakdown:
javascript
const str = "hello world";
const result = str.split(' ')
                .map(word => {
                    console.log(word.charAt(0)); // Actual Output: h, w
                    return word.charAt(0);
                })
                .join('');
console.log(result); // Actual Output: hw
Using split, map and join to get first letter of each word in string

Explanation:

  • split(' '): Splits the string into an array of words using a space as the delimiter.
  • map(word => word.charAt(0)): Maps each word to its first letter using the charAt(0) method.
  • join(''): Joins the array of first letters back into a single string.

Method 2: Using Regular Expressions

For regex enthusiasts, we can get all words using regex pattern /b/w, and then like previous approach we map every word to initials, and then join the initials.

javascript
const str = "hello world";
  
const result = str.match(/w/g).map(letter => {
  console.log(letter); // Actual Output: h, w
  return letter;
}).join('');

console.log(result); // Actual Output: hw
Using regular expression to get all words, then map every word to initials, and join

Regex symbols Explanation:

  • /: Denotes the beginning of the regular expression.
  • \b: Matches a word boundary.
  • \w: Matches any word character (alphanumeric + underscore).
  • g: Global flag for matching all occurrences in the string.
  • The combination of \b\w ensures we capture the first letter of each word.

Method 3: Using .reduce()

This functional approach involves reducing the array of words to accumulate their first letters:

javascript
const str = "hello world";
const result = str.split(' ')
                .reduce((acc, word) => {
                    console.log(acc + word[0]); // Actual Output: h, hw
                    return acc + word[0];
                }, '');
console.log(result); // Actual Output: hw
reduce() to accumulate first letters

Explanation:

  • split(' '): Splits the string into an array of words.
  • reduce((acc, word) => acc + word[0], ''): Iterates over the array, accumulating the first letter of each word.

Method 4: Using Array Destructuring

Unpack those letters elegantly using array destructuring:

javascript
const str = "hello world";
const result = str.split(' ')
                .map(([firstLetter]) => {
                    console.log(firstLetter); // Actual Output: h, w
                    return firstLetter;
                })
                .join('');
console.log(result); // Actual Output: hw
Using Array Destructuring to extract first letters
  • ([firstLetter]): Destructures the array to directly access the first letter.

Common errors

Handling Punctuation:

To include punctuation following a word (e.g., “Hello!”), modify the regular expression or adjust the handling accordingly.

javascript
const str = "hello, world!";
const result = str.match(/w|W/g).map(letter => {
  console.log(letter); // Actual Output: h, e, l, l, o, ,, w, o, r, l, d, !
  return letter;
}).join('');
console.log(result); // Actual Output: helloworld!
Handling Puncutations
  • \W: Matches any non-word character, including punctuation.

Empty String Handling:

Ensure your code accounts for empty input strings to prevent unexpected results. In all methods, an empty string would produce an empty result.


🧪Practice Coding Problem: Initials Generator

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

Implement a function that upgrades each element in an array by squaring it

Problem (JavaScript)

javascript
/**
* Generates initials from a full name.
*
* @param {string} fullName - The full name to extract initials from.
* @returns {string} - The generated initials.
*/
function generateInitials(fullName) {
  // > > > 👉 Write code here 👈 < < <
}

// Example:
const initials = generateInitials("john doe");
console.log(initials); // Output: "JD"
Problem Code

Please attempt before seeing the Answer:

Solution
javascript
function generateInitials(fullName) {
  if (!fullName || typeof fullName !== 'string') {
      return 'Invalid input';
  }

  // Split the full name into an array of names
  const names = fullName.trim().split(/s+/);
  let initials = '';

  for (const name of names) {
      if (name.length > 0) {
          // Capitalize and append the first letter of each name
          initials += name[0].toUpperCase();
      }
  }

  return initials;
}
Solution Code

Explanation:

  • fullName.trim(): Removes leading and trailing whitespaces from the full name.
  • split(/\\s+/): Splits the trimmed full name into an array of names, considering one or more consecutive whitespaces as the delimiter.
  • Iterate over the names, capitalize the first letter of each name, and append it to the initials string.
  • Return the resulting initials string.

Why do programmers prefer dark mode? Because light attracts bugs. 😉

Happy coding, and may your code be as clean as your favorite editor theme! 🚀

Contact

Feel free to reach out!