In my React application there’s the following function which generates the user initials from the first name/last name like so:
@computed public get initials() {
const firstNameLetter = this.firstName
? this.firstName[0].toLocaleUpperCase()
: '';
const lastNameLetter = this.lastName
? this.lastName[0].toLocaleUpperCase()
: '';
return `${firstNameLetter}${lastNameLetter}`;
}
This works fine. But if the first name or the last name starts with an emoji, this code is basically breaking that emoji and what is displayed is just a question mark. The problem is with taking the first char which is not enough if it’s an emoji and it is eventually breaking it.
Is anybody aware of any way of detecting that the first element is an emoji and treat it correspondingly? Or maybe there’s a better way of creating the initials other than this kind of split which will deal with emojis as well?
2
Answers
an easy fix would be to create an array using spread and then get the first element
edit
didn’t realize that there can be so many edge cases as 0stone0 mentioned in the comments. For a more sophisticated splitting this has better answers
Why we can’t use array.from method here instead of split