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
Return Vowels in a string in JavaScript
We are required to write a JavaScript function that takes in a string that might contain some alphabets. The function should count and return the number of vowels that exists in the string.
Syntax
function countVowels(str) {
// Convert to lowercase for case-insensitive comparison
// Loop through each character
// Check if character is a vowel (a, e, i, o, u)
// Return the count
}
Example: Using for Loop
Following is the code ?
const str = 'this is a string';
const countVowels = (str = '') => {
str = str.toLowerCase();
const legend = 'aeiou';
let count = 0;
for(let i = 0; i < str.length; i++){
const el = str[i];
if(!legend.includes(el)){
continue;
}
count++;
}
return count;
};
console.log(countVowels(str));
console.log(countVowels('Hello World'));
console.log(countVowels('JavaScript'));
Output
Following is the output on console ?
4 3 3
Using Regular Expressions
A more concise approach using regular expressions:
const countVowelsRegex = (str = '') => {
const matches = str.toLowerCase().match(/[aeiou]/g);
return matches ? matches.length : 0;
};
console.log(countVowelsRegex('this is a string'));
console.log(countVowelsRegex('Hello World'));
console.log(countVowelsRegex('bcdfg'));
4 3 0
Using Array Methods
Using modern JavaScript array methods for a functional approach:
const countVowelsArray = (str = '') => {
const vowels = 'aeiou';
return str.toLowerCase()
.split('')
.filter(char => vowels.includes(char))
.length;
};
console.log(countVowelsArray('this is a string'));
console.log(countVowelsArray('Programming'));
console.log(countVowelsArray('xyz'));
4 3 0
Comparison
| Method | Performance | Readability | Code Length |
|---|---|---|---|
| For Loop | Fastest | Good | Long |
| Regular Expression | Medium | Excellent | Short |
| Array Methods | Slowest | Excellent | Medium |
Conclusion
Use the for loop method for performance-critical applications, or the regex approach for cleaner, more readable code. All methods handle case-insensitive vowel counting effectively.
Advertisements
