Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
- Split the input string into an array of words using space as delimiter
- Iterate through each word in the array
- Extract the first character of each word using destructuring assignment
- Check if the character is uppercase by comparing it with its uppercase version
- Also ensure it's actually a letter (not a number or symbol) by checking it's different from its lowercase version
- 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.
