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
Selected Reading
Counting number of vowels in a string with JavaScript
We are required to write a JavaScript function that takes in a string. The function should count the number of vowels present in the string.
The function should prepare an object mapping the count of each vowel against them.
Example
The code for this will be ?
const str = 'this is an example string';
const vowelCount = (str = '') => {
const splitString = str.split('');
const obj = {};
const vowels = "aeiou";
splitString.forEach((letter) => {
if(vowels.indexOf(letter.toLowerCase()) !== -1){
if(letter in obj){
obj[letter]++;
} else {
obj[letter] = 1;
}
}
});
return obj;
};
console.log(vowelCount(str));
Output
And the output in the console will be ?
{ i: 3, a: 2, e: 2 }
Alternative Method Using Regular Expressions
Here's another approach using regular expressions to match vowels:
const vowelCountRegex = (str = '') => {
const vowels = str.toLowerCase().match(/[aeiou]/g) || [];
const obj = {};
vowels.forEach(vowel => {
obj[vowel] = (obj[vowel] || 0) + 1;
});
return obj;
};
console.log(vowelCountRegex('Hello World'));
console.log(vowelCountRegex('JavaScript Programming'));
{ e: 1, o: 2 }
{ a: 2, i: 1, o: 2, a: 1, i: 1 }
Enhanced Version with Total Count
This version returns both individual vowel counts and the total vowel count:
const vowelAnalysis = (str = '') => {
const vowels = "aeiou";
const counts = {};
let total = 0;
for(let char of str.toLowerCase()) {
if(vowels.includes(char)) {
counts[char] = (counts[char] || 0) + 1;
total++;
}
}
return {
vowels: counts,
total: total
};
};
console.log(vowelAnalysis('The quick brown fox'));
{ vowels: { e: 1, u: 1, i: 1, o: 2 }, total: 5 }
Conclusion
These methods effectively count vowels in strings using different approaches. The forEach method provides clear logic, while regular expressions offer a more concise solution for vowel matching.
Advertisements
