Returning acronym based on a string in JavaScript

We need to write a JavaScript function that creates an acronym from a string by taking the first letter of each word that starts with an uppercase letter.

The function should build and return the acronym based on the string phrase provided as input. While constructing the acronym, the function should only consider words that start with an uppercase letter.

Problem Statement

Given a string like "Polar Satellite Launch Vehicle", we want to extract the first letter of each capitalized word to form "PSLV".

Input: 'Polar Satellite Launch Vehicle'
Output: 'PSLV'

Solution

Here's how we can implement this function:

const str = 'Polar Satellite Launch Vehicle';

const buildAcronym = (str = '') => {
    const strArr = str.split(' ');
    let res = '';
    
    strArr.forEach(word => {
        const [firstChar] = word;
        if(firstChar === firstChar.toUpperCase() && firstChar !== firstChar.toLowerCase()){
            res += firstChar;
        }
    });
    
    return res;
};

console.log(buildAcronym(str));
console.log(buildAcronym('Bachelor of Science'));
console.log(buildAcronym('world Health Organization'));
PSLV
BS
HO

How It Works

The function follows these steps:

  1. Split the input string into an array of words using space as delimiter
  2. Iterate through each word in the array
  3. Extract the first character of each word using destructuring assignment
  4. Check if the character is uppercase by comparing it with its uppercase version
  5. Also ensure it's actually a letter (not a number or symbol) by checking it's different from its lowercase version
  6. If both conditions are met, add the character to the result string

Alternative Implementation

Here's a more concise version using array methods:

const buildAcronymConcise = (str = '') => {
    return str.split(' ')
        .filter(word => word[0] && word[0] === word[0].toUpperCase() && word[0] !== word[0].toLowerCase())
        .map(word => word[0])
        .join('');
};

console.log(buildAcronymConcise('Polar Satellite Launch Vehicle'));
console.log(buildAcronymConcise('National Aeronautics and Space Administration'));
PSLV
NASA

Key Points

  • The condition char !== char.toLowerCase() ensures we only process actual letters, not numbers or symbols
  • Words starting with lowercase letters (like "of", "and") are ignored
  • Empty strings or words are handled gracefully
  • The function preserves the order of words in the original string

Conclusion

This function effectively creates acronyms by filtering words that start with uppercase letters and combining their first characters. It's useful for generating abbreviations from proper nouns and titles.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements