Abbreviate a two word name with replace()

Viewed 86

Does anybody know why this function doesn't return the second initial? Expected: 'S.H', instead got: 'S. '

function abbrevName('Sam Hayes'){
  let initials = 'x.x';
  for (let i = 0; i < name.length; i++) {
    if (name[i] === name[i].toUpperCase()) {
      initials = initials.replace('x', name[i]);
    } 
  }
  return initials;
}
3 Answers

Its the space beeng recognized as uppercase

function abbrevName(name){
  let initials = 'x.x'
     for (let i = 0; i < name.length; i++) {
       if (name[i] === name[i].toUpperCase() && name[i]!= " ") {
         console.log(name[i].toUpperCase())
         initials = initials.replace('x', name[i])
       } 
     }
  return initials;
}


console.log(abbrevName('Sam Hayes'))

Instead of name[i] === name[i].toUpperCase(), you need to do name[i].toLowerCase() === name[i].toUpperCase() since the space will pass the former check.

you can use Array.split() instead for example

function abbrevName(name){
  const arr = name.split(" ");
  const initials = arr[0][0]+"."+arr[1][0];
  return initials 
 }
Related