Get first letter of each Word in a String in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20212 min read

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 to get the first letter of each word in a string.

We used the the String.split method on the string and split it on each space. This returns an array containing the words in the string.

index.js
// ๐Ÿ‘‡๏ธ ['Hello', 'world'] console.log('Hello world'.split(' '));

The next step is to call the Array.map method on the array of words.

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 our case these are the first letters 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 takes a separator as a parameter. Because we want to get a string containing just the letters, we pass the method an empty string.

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee