javascriptabbreviation

How do I write a function in JS to return abbreviation of the words?


For example:

makeAbbr('central processing unit') === 'CPU'

I could not find my mistake. I appreciate your help.

function makeAbbr(words) {
  let abbreviation = words[0];
  for (let i = 1; i < words.length; i++) {
    if (words[i] === '') {
      abbreviation += words[i + 1];
    }
  }
  return abbreviation.toUpperCase();
}

console.log(makeAbbr('central processing unit'));


Solution

  • You just need to change the words[i] === '' into words[i] === ' '. '' is an empty string.

    Another option is splitting the passed string.

    function makeAbbr(str) {
       // words is [ "central", "processing", "unit" ]
       let words = str.split(/\s+/);
       let abbreviation = '';
       for (let i = 0; i < words.length; i++) {
         abbreviation += words[i][0];
       }
       return abbreviation.toUpperCase();
    }