Borislav Hadzhiev
Fri Oct 22 2021·2 min read
Photo by Rafael Leão
To get the first letter of each word in a string:
split()
method on the string to get an array containing the words
in the string.map()
method to iterate over the array and return the first letter
of each word.join()
method.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 String.split method on the string and split it on each space. This returns an array containing the words in the string.
// 👇️ ['Hello', 'world'] console.log('Hello world'.split(' '));
The next step is to call the Array.map method on the array of words.
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.
// 👇️ ['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.
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'));