skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. Why we can’t use array.from method here instead of split

    const firstName = '😀ey';
    
    const res = Array.from(firstName);
    
    
    console.log(res);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search