In this blog post, we’ll explore a common coding challenge: counting the number of vowels in a string. This exercise helps you practice string manipulation, loops, and conditionals in JavaScript. We’ll start with a basic approach and then look at ways to optimize and simplify the solution.
Problem Statement
Write a function that returns the number of vowels used in a given string. The vowels are the characters a
, e
, i
, o
, and u
, and the function should be case-insensitive.
Examples:
vowels('Hi There!'); // Output: 3
vowels('Why do you ask?'); // Output: 4
vowels('Why?'); // Output: 0
Initial Solution
Let’s start with an approach where we use two loops: an outer loop to iterate over each character in the string, and an inner loop (or forEach()
) to check if each character is a vowel.
Here’s the initial solution:
function vowels(str) {
const arr = ['a', 'e', 'i', 'o', 'u'];
const search = str.split('');
let count = 0;
// Loop through each character in the string
for (let i = 0; i < search.length; i++) {
// Check if the current character matches any vowel in the array
arr.forEach((c) => {
search[i] === c ? count++ : '';
});
}
return count;
}
// Test cases
console.log(vowels('Hi There!')); // Output: 3
console.log(vowels('Why do you ask?')); // Output: 4
console.log(vowels('Why?')); // Output: 0
Explanation
- Splitting the String: We first convert the input string into an array of characters.
- Checking Each Character: For each character in the array, we check if it matches any vowel from the
arr
array. - Counting Vowels: If a match is found, we increment the
count
variable.
Optimizing the Solution
While the initial solution works, it can be simplified. We can improve the code using the following techniques:
- Using the
includes()
Method: Instead of checking each character withforEach()
, we can useincludes()
to see if a character is a vowel. - Using a
for...of
Loop: This will make the code more readable when iterating over characters.
Here’s the refactored solution:
function vowels(str) {
const arr = ['a', 'e', 'i', 'o', 'u'];
let count = 0;
// Loop through each character in the string
for (let char of str.toLowerCase()) {
// Check if the character is a vowel
if (arr.includes(char)) {
count++;
}
}
return count;
}
// Test cases
console.log(vowels('Hi There!')); // Output: 3
console.log(vowels('Why do you ask?')); // Output: 4
console.log(vowels('Why?')); // Output: 0
Explanation of the Optimized Solution
- Convert to Lowercase: We convert the string to lowercase to make the comparison case-insensitive.
- Use
for...of
Loop: This simplifies iterating over each character in the string. - Check with
includes()
: Theincludes()
method checks if the current character is a vowel, making the code more concise.
Alternative Approach Using Regular Expressions
Another way to solve this problem is by using regular expressions. This approach uses a regular expression to match vowels and count them.
function vowels(str) {
const matches = str.match(/[aeiou]/gi);
return matches ? matches.length : 0;
}
// Test cases
console.log(vowels('Hi There!')); // Output: 3
console.log(vowels('Why do you ask?')); // Output: 4
console.log(vowels('Why?')); // Output: 0
How It Works:
- Regular Expression
/[aeiou]/gi
:
[aeiou]
: Matches any vowel character.g
: Global flag to find all matches.i
: Case-insensitive flag.
match()
Method: Returns an array of all matches, ornull
if no matches are found.- Count the Matches: If
match()
returns an array, its length gives the number of vowels; otherwise, return 0.
Comparison of Approaches
Approach | Pros | Cons |
---|---|---|
Loop with includes() | Easy to understand, no extra memory allocation. | Slightly more verbose. |
Regular Expression | Concise, easy to implement for this problem. | Requires familiarity with regex. |
Performance Considerations
For small to medium-sized strings, both approaches will perform similarly. However, the regular expression method may have a slight overhead due to pattern matching, while the loop approach may have a slight advantage with longer strings.
Key Takeaways
- String Manipulation: This exercise emphasizes various string manipulation techniques in JavaScript.
- Loops and Conditionals: Knowing different ways to iterate through a string helps in solving problems efficiently.
- Regular Expressions: Using regex can simplify code but requires understanding pattern matching.
Conclusion
Finding vowels in a string is a simple but valuable coding challenge for beginners. It introduces string manipulation, conditionals, and different coding approaches. Try the exercise using different techniques and see which one you prefer!