Returning acronym based on a string in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in a string of characters as the only argument.

The function should build and return the acronym based on the string phrase provided as input.

While constructing the acronym the function should take only those words into consideration that starts with an uppercase letter.

For example −

If the input string is −

const str = 'Polar Satellite Launch Vehicle';

Then the output should be −

const output = 'PSLV';

Example

Following is the code −

const str = 'Polar Satellite Launch Vehicle';
const buildAcronym = (str = '') => {
   const strArr = str.split(' ');
   let res = '';
   strArr.forEach(el => {
      const [char] = el;
      if(char === char.toUpperCase() && char !== char.toLowerCase()){
         res += char;
      };
   });
   return res;
};
console.log(buildAcronym(str));
console.log(buildAcronym('Bachelor of Science'));

Output

Following is the console output −

PSLV
BS
raja
Published on 23-Jan-2021 06:37:39
Advertisements