Generating user initials if the name or surname starts with an emojis

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?

6

2 Answers

an easy fix would be to create an array using spread and then get the first element

const firstName = '😀ey' console.log(firstName[0]) //split doesnt work const firstNameArrSplit = firstName.split("") console.log(firstNameArrSplit) const firstNameArrSpread = [...firstName] console.log(firstNameArrSpread) console.log(firstNameArrSpread[0])
@computed public get initials() { const firstNameLetter = this.firstName ? [...this.firstName][0].toLocaleUpperCase() : ''; const lastNameLetter = this.lastName ? [...this.lastName][0].toLocaleUpperCase() : ''; return `${firstNameLetter}${lastNameLetter}`; } 

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

2

Why we can't use array.from method here instead of split

const firstName = '😀ey'; const res = Array.from(firstName); console.log(res);

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like