Get first letter of each Word in a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Get first letter of each Word in a String #

To get the first letter of each word in a string:

  1. Call the split() method on the string to get an array containing the words in the string.
  2. Call the map() method to iterate over the array and return the first letter of each word.
  3. Join the array of first letters into a string, using the join() method.
index.js
function getFirstLetters(str) { const firstLetters = str .split(' ') .map(word => word[0]) .join(''); return firstLetters; } // 👇️ ABC console.log(getFirstLetters('Alice, Bob, Charlie')); // 👇️ ONE console.log(getFirstLetters('Oscar Noah Emily.'));

We created a reusable function that returns the first letter of each word in a string.

We used the String.split to split the string on each space.

The array we got back from the split method contains the words in the string.

index.js
// 👇️ ['Hello', 'world'] console.log('Hello world'.split(' '));

We used the Array.map to iterate over the array.

The function we passed to the map method gets called with each element (word) in the array.

The map method returns a new array containing the values the callback function returned.

In this case, an array containing the first letter of each word.

index.js
// 👇️ ['H', 'w'] console.log('Hello world'.split(' ').map(word => word[0]));

The last step is to call the Array.join method to join the array into a string.

The join() method joins an array of strings based on the provided separator.

We want to get a string containing only the letters, so we passed an empty string to the join() method.

Here's the complete code snippet.

index.s
function getFirstLetters(str) { const firstLetters = str .split(' ') .map(word => word[0]) .join(''); return firstLetters; } // 👇️ Hw console.log(getFirstLetters('Hello world')); // 👇️ OTT console.log(getFirstLetters('One, Two, Three'));

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.