skip to Main Content

I wanted to retrieve the first letters of a person’s first name and last name using modern JavaScript syntax. Currently, I’m able to retrieve the first letter of the first name and the first letter of the last name correctly.

My problem is that if there’s no "of" word, I can’t retrieve it.

Here’s my Jsfiddle link —-> CLICK HERE

CODE:

/* const name = "Joshua Jones of USA"; */
const name = "William Sanders";
/* const name = "Grey Charles"; */

function getUserInitials(name) {
  return /^(.).+([A-Z])w+sofs.+$/.exec(name).slice(1, 3).join('');
}


console.log(getUserInitials(name));

2

Answers


  1. Not sure what exactly you’re trying to do, but this solves the shown test cases:

    const names = ["Joshua Jones of USA", "William Sanders", "Grey Charles"];
    
    function getUserInitials(name) {
      return name.split(' ').map(w => w.charAt(0).toUpperCase()).splice(0,2);
    }
    
    for (const name of names)
      console.log(getUserInitials(name));

    If this doesn’t satisfy your requirements, then please elaborate on those.

    Login or Signup to reply.
  2. If your test cases cover all possible formats, you can either improve your regexp:

    function getUserInitials(name) {
        const matches = /^(.).*?s+(.).*$/.exec(name);
        if (matches) {
            return matches.slice(1, 3).join('').toUpperCase();
        } else {
            return '';
        }
    }
    
    console.log(getUserInitials("Joshua Jones of USA"));
    console.log(getUserInitials("William Sanders"));
    console.log(getUserInitials("Grey Charles"));

    or you can split by "of" first, and then split by whitespaces:

    function getUserInitials(name) {
        const [firstName, lastName] = name.split('of')[0].trim().split(' ');
    
        return `${firstName[0]}${lastName[0]}`.toUpperCase();
    }
    
    console.log(getUserInitials("Joshua Jones of USA"));
    console.log(getUserInitials("William Sanders"));
    console.log(getUserInitials("Grey Charles"));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search