Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Retrieving Some Texts in Javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

CODE:

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

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


console.log(getUserInitials(name));

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading