Finding Vowels in a String Using JavaScript

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

  1. Splitting the String: We first convert the input string into an array of characters.
  2. Checking Each Character: For each character in the array, we check if it matches any vowel from the arr array.
  3. 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:

  1. Using the includes() Method: Instead of checking each character with forEach(), we can use includes() to see if a character is a vowel.
  2. 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

  1. Convert to Lowercase: We convert the string to lowercase to make the comparison case-insensitive.
  2. Use for...of Loop: This simplifies iterating over each character in the string.
  3. Check with includes(): The includes() 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:

  1. Regular Expression /[aeiou]/gi:
  • [aeiou]: Matches any vowel character.
  • g: Global flag to find all matches.
  • i: Case-insensitive flag.
  1. match() Method: Returns an array of all matches, or null if no matches are found.
  2. Count the Matches: If match() returns an array, its length gives the number of vowels; otherwise, return 0.

Comparison of Approaches

ApproachProsCons
Loop with includes()Easy to understand, no extra memory allocation.Slightly more verbose.
Regular ExpressionConcise, 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

  1. String Manipulation: This exercise emphasizes various string manipulation techniques in JavaScript.
  2. Loops and Conditionals: Knowing different ways to iterate through a string helps in solving problems efficiently.
  3. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *