How to use Iterative Approach In Javascript

In this iterative approach, we loop through each character of the string. Lowercasing ensures case insensitivity. By checking if a character falls between ‘a’ and ‘z’ and is not among ‘aeiou’, we identify consonants and increment the count. This method provides a simple and clear way to count consonants in a string.

Example: Implementation to find number of consonants in a string using iterative approach.

JavaScript
let str = "Hello GFG";
let cnt = 0;
for (let i = 0; i < str.length; i++) {
    let char = str.charAt(i).toLowerCase();
    if (char >= 'a' && char <= 'z' && !'aeiou'.includes(char)) {
        cnt++;
    }
}
console.log("Number of consonants:", cnt);

Output
Number of consonants: 6

Time Complexity: O(n)

Auxiliary Space: O(1)

Find Number of Consonants in a String using JavaScript

In JavaScript, counting the number of consonants in a string can be achieved through various approaches. Consonants are the letters excluding vowels (a, e, i, o, u).

Examples: 

Input : abcde
Output : 3
There are three consonants b, c and d.

Input : w3wiki portal
Output : 12

Table of Content

  • Using Iterative Approach
  • Using Regular Expressions
  • Using ES6 Array Functions

Similar Reads

Using Iterative Approach

In this iterative approach, we loop through each character of the string. Lowercasing ensures case insensitivity. By checking if a character falls between ‘a’ and ‘z’ and is not among ‘aeiou’, we identify consonants and increment the count. This method provides a simple and clear way to count consonants in a string....

Using Regular Expressions

In this approach, we are using a regular expression /[bcdfghjklmnpqrstvwxyz]/gi to match all consonants (case-insensitive) in the string. The match method returns an array of matches, and we determine the number of consonants by the length of this array....

Using ES6 Array Functions

In this method utilizing ES6 array functions such as filter and reduce, we split the string into an array of characters. Using filter, we extract consonants based on a defined condition and then return the count using reduce. This approach offers a succinct and modern solution for counting consonants in a string....

Contact Us