DEV Community

Discussion on: Which functions/methods do you...

Collapse
 
siddsarkar profile image
Siddhartha Sarkar

This is one I made and using across many projects.

/**
 * Takes full name and converts into initials
 * @param {string} string full name of user e.g John Doe
 * @returns initials e.g JD
 */
const getInitials = (string = '') =>
  string
    .split(' ')
    .map(([firstLetter]) => firstLetter)
    .filter((_, index, array) => index === 0 || index === array.length - 1)
    .join('')
    .toUpperCase()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

It seems a bit overcomplicated to me, I'd do something like:

const getInitials = (str = '') =>  str.split(' ').map( part => part.charAt(0).toUpperCase()).join('');
Enter fullscreen mode Exit fullscreen mode

I think it does the same but... Am I missing something maybe? Probably some use case that is not in my mind πŸ˜…

Collapse
 
kamil7x profile image
Kamil Trusiak

For input like Mary Jane Watson, your function returns MJW, and his returns MW.
It's common practice to use only two letters as initials on avatars (eu.ui-avatars.com/api/?name=Mary+J...)

Thread Thread
 
joelbonetr profile image
JoelBonetR πŸ₯‡ • Edited

That was one of my first thoughts but initials depend on the country, so my name is Joel Bonet Rxxxxx, being Joel my name and Bonet + Rxxxxx my two surnames.
So in this case I'll be JR with this approach which in my country and according to my culture or what is reasonable, it should be JB. (first character of the name + first character of the surname).

That's the main reason for getting separate fields for name and surname/s.

So your name can be "Mary Jane Linda" and your surnames can be "Lee Bonet".

const initials = `${user.name.charAt(0).toUpperCase()}${user.surname.charAt(0).toUpperCase()}`; 
Enter fullscreen mode Exit fullscreen mode

and still getting ML as initials which would be the most correct output as far as I can tell.

Thread Thread
 
kevinleebuchan profile image
KevinLeeBuchan

Here I am enjoying all the great, open conversations about programming and now I learn something about other cultures too. #Winning

Collapse
 
siddsarkar profile image
Siddhartha Sarkar

You must restrict your initials to some letter count either one or two, see your initial from the above fn will grow with no. of words in a name which is not favourable to be called 'initials'

And yes my country surnames is at last so picking the last one in my code πŸ˜