Open In App

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 : geeksforgeeks portal
Output : 12

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.

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

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)

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.

Example: Implementation to find number of consonants in a string using regular expressions.

let str = "Hello GFG";
let cnt = str.match(/[bcdfghjklmnpqrstvwxyz]/gi).length;
console.log("Number of consonants:", cnt);

Output
Number of consonants: 6

Time Complexity: O(n)

Auxiliary Space: O(n)

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.

Example: Implementation to find number of consonants in a string using ES6 array functions.

function countConsonants(str) {
    // Convert the string to lowercase to handle case insensitivity
    str = str.toLowerCase();
    // Use filter to get an array of consonants
    const consonants = str.split('').filter(
        char => 'bcdfghjklmnpqrstvwxyz'.includes(char));
    // Return the count of consonants
    return consonants.length;
}

// Example usage
const str = "Hello World";
console.log(countConsonants(str)); // Output: 7

Output
7

Time Complexity: O(n)

Auxiliary Space: O(n)

Article Tags :