There are many complicated answers here...
Simpler solution with Clean code!
I know this question has been around for a while, but I believe this solution is good enough to share with you :)
My goal with this code is to create something that is both intelligent and easy to read.
const names = [
'Crystals', // -> CR
'undisclosed desires', // -> UD
'Feel so Close - Radio Edit', // -> FE
' ', // -> empty
'Faint ', // -> FA .: Note the space after the name
]
function getInitials(fullName) {
const [firstName, ...restNames] = fullName.toUpperCase().trim().split(' ')
if (!restNames.length) {
return firstName.substring(0,2)
}
const firstNameInitial = firstName[0]
const lastNameInitial = restNames.pop()[0]
return `${firstNameInitial}${lastNameInitial}`
}
console.log(names.map(getInitials))
The first line, transforms the string to uppercase, remove unwanted spaces (at the begginning and end) and split the name creating an array. Using the destructuring we recover the firstName
and place the rest into a constant called restNames
const [firstName, ...restNames] = fullName.toUpperCase().trim().split(' ')
after that, we check if there's other names besides the first name, if not, we return the first two letters from it ending the function execution
if (!restNames.length) {
return firstName[0].substring(0,2)
}
If we found out that restNames contains other names, we get the first name and the last name initials
const firstNameInitial = firstName[0]
const lastNameInitial = restNames.pop()[0]
Finally, we return the initials!
return `${firstNameInitial}${lastNameInitial}`
This code aims to be clear and efficient in providing the desired result