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

Get initials of names in Javascript

I have Person and group names

Person :

Robert Smith
David Smith
James Johnson
William

if i use this code

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

if(Name.split(",").length === 1)
  return Name.trim().split(" ").map(x => x[0]).reduce((acc, curr) => acc + curr) 
else 
  return ''

Output is

  1. RS
  2. DS
  3. JJ

but in my second scenario there are sets of names

like

  1. Robert Smith,David Smith
  2. James Johnson,Robert Smith

in this case if any comma is found i want to return RD in first case and in second case JS

>Solution :

Your question is not clear, I assume you need to get the initial of the first and last name in the first scenario and get the initial of each name in the second scenario.

Check whether the following solution helps,

const scenario1 = "Robert Smith";
const scenario2 = "Robert Smith,David Smith";

function getInitial(data) {

  const chunks = data.split(",");
  
  if ( chunks.length > 1) {
    const initials = [];
    chunks.forEach(chunk => initials.push(chunk[0]));
    return initials.join('');
  } else {
    const [fname, lname] = chunks[0].split(' ');
    return `${fname[0]}${(lname ? lname[0] : '')}`;
  }

}

console.log(getInitial(scenario1))
console.log(getInitial(scenario2))
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