Index Of /

Get Initials from Full Name

April 9, 2020

It's been a while since my last post. Again. A lot of big ideas on what to write about, but like every big idea — no time to bring it to life.

Today I'd like to share with you a small function that extracts initials from the full name string. Initials are often used to build an avatar when no image is available. That is my case too.

I have built a chain of transformations to extract the initials. Because, IMHO, its easier to understand than some of the fascinating Regular Expressions you can find on Stack Overflow.

Also, it was the first time I was using the new Unicode supporting pattern to filter letters in all alphabets \p{L} with the u flag.

export const getInitialsFromName = (name: string): string => { 
let initials = name
.replace(/[^\p{L}\s]|_|\d/ug, '') // remove all non letters from the string
.replace(/\s+/g, ' ') // trailing space to single char
.replace(/^\s+|\s+$/g, '') // remove spaces in the begining and the end
.split(' ') // split the string to the array of names
.filter((word, index, arr) => index === 0 || index === arr.length - 1)
// get the first and last names only
.map(word => word.substr(0, 1)) // get the first letters from the names
.join('') // convert to string
.toUpperCase(); // and make the initials uppercased

if (initials.length === 0) {
return '#'; // in our case, if there are no initals it's a number
return initials.substr(0, 2); // return just the first two letters from the name
Andrey “Leechy” Lechev

Some frontender thoughts
Twitter, GitHub, LinkedIn