Count consonants in a string javascript

The main problem in counts lies within your conditions.

You're increasing the number of consonants whenever one of the conditions fail (that's what || does, known as the OR operator). So whenever a character !== "a" OR !== "e", you're increasing the count, which is wrong. (Imagine that a is !== 'e', so you're counting a as a consonant).

Change the || binary operator to && (AND); this way, you're only increasing the consonant count whenever the current character str[i] is not among the values you're verifying for (a, e, i, o, u, ' ').

As others pointed out, you're also likely to run into an error as the max value of i should be Length-1.

There also other problems you need to consider:

  • What happens when the character is an uppercase letter?
  • What happens when the character is a punctuation mark or a number?

For a beginner, this may not be relevant, but it's well worth getting these techniques under your skin: It's more readable to create an array that contains all of the value you're verifying for ["a","e", etc] and then, for each char in the source string, just verify if array.indexOf(str[i]) >= 0 (which means that the character is included in the array).

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a string, count total number of consonants in it. A consonant is a English alphabet character that is not vowel (a, e, i, o and u). Examples of constants are b, c, d, f, g, ..

    Examples : 

    Input : abc de
    Output : 3
    There are three consonants b, c and d.
    
    Input : geeksforgeeks portal
    Output : 12

     1. Iterative Method 

    C++

    #include

    using namespace std;

    bool isConsonant(char ch)

    {

        ch = toupper(ch);

        return !(ch == 'A' || ch == 'E' ||

                ch == 'I' || ch == 'O' ||

                ch == 'U') && ch >= 65 && ch <= 90;

    }

    int totalConsonants(string str)

    {

        int count = 0;

        for (int i = 0; i < str.length(); i++)

            if (isConsonant(str[i]))

                ++count;

        return count;

    }

    int main()

    {

        string str = "abc de";

        cout << totalConsonants(str);

        return 0;

    }

    Java

    import java.io.*;

    class GFG {

        static boolean isConsonant(char ch)

        {

            ch = Character.toUpperCase(ch);

            return !(ch == 'A' || ch == 'E' ||

                    ch == 'I' || ch == 'O' ||

                    ch == 'U') && ch >= 65 && ch <= 90;

        }

        static int totalConsonants(String str)

        {

            int count = 0;

            for (int i = 0; i < str.length(); i++)

                if (isConsonant(str.charAt(i)))

                    ++count;

            return count;

        }

        public static void main(String args[])

        {

            String str = "abc de";

            System.out.println( totalConsonants(str));

        }

    }

    Python3

    def isConsonant(ch):

        ch = ch.upper()

        return not (ch == 'A' or ch == 'E' or

                    ch == 'I' or ch == 'O' or

                    ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90

    def totalConsonants(string):

        count = 0

        for i in range(len(string)):

            if (isConsonant(string[i])):

                count += 1

        return count

    string = "abc de"

    print(totalConsonants(string))

    C#

    using System;

    class GFG {

        static bool isConsonant(char ch)

        {

            ch = Char.ToUpper(ch);

            return !(ch == 'A' || ch == 'E' ||

                     ch == 'I' || ch == 'O' ||

                     ch == 'U') && ch >= 65 && ch <= 90;

        }

        static int totalConsonants(String str)

        {

            int count = 0;

            for (int i = 0; i < str.Length; i++)

                if (isConsonant(str[i]))

                    ++count;

            return count;

        }

        public static void Main()

        {

            String str = "abc de";

            Console.Write( totalConsonants(str));

        }

    }

    PHP

    function isConsonant($ch)

    {

        $ch = strtoupper($ch);

        return !($ch == 'A' || $ch == 'E' ||

                $ch == 'I' || $ch == 'O' ||

                $ch == 'U') && ord($ch) >= 65 && ord($ch) <= 90;

    }

    function totalConsonants($str)

    {

        $count = 0;

        for ($i = 0; $i < strlen($str); $i++)

            if (isConsonant($str[$i]))

                ++$count;

        return $count;

    }

    $str = "abc de";

    echo totalConsonants($str);

    return 0;

    ?>

    Javascript

          function totalConsonants(str) {

            var count = 0;

            for (var i = 0; i < str.length; i++)

              if (isConsonant(str[i])) ++count;

            return count;

          }

          var str = "abc de";

          document.write(totalConsonants(str));

        

    Time Complexity: O(n), where n is the length of the string
    Auxiliary Space: O(1)

     2. Recursive Method 

    C++

    #include

    using namespace std;

    bool isConsonant(char ch)

    {

        ch = toupper(ch);

        return !(ch == 'A' || ch == 'E' ||

                ch == 'I' || ch == 'O' ||

                ch == 'U') && ch >= 65 && ch <= 90;

    }

    int totalConsonants(string str, int n)

    {

        if (n == 1)

            return isConsonant(str[0]);

        return totalConsonants(str, n - 1) +

               isConsonant(str[n-1]);

    }

    int main()

    {

        string str = "abc de";

        cout << totalConsonants(str, str.length());

        return 0;

    }

    Java

    import java.util.*;

    import java.lang.*;

    class GFG

    {

    static boolean isConsonant(char ch)

    {

        ch = Character.toUpperCase(ch);

        return (ch == 'A' || ch == 'E' ||

                ch == 'I' || ch == 'O' ||

                ch == 'U')== false && ch >= 65 && ch <= 90;

    }

    static int totalConsonants(String str, int n)

    {

        if (n == 1)

        {

            if(isConsonant(str.charAt(0)))

                return 1;

            else

                return 0;

        }

        if(isConsonant(str.charAt(n - 1)))

            return totalConsonants(str, n - 1) + 1;

        else

            return totalConsonants(str, n - 1);

    }

    public static void main(String args[])

    {

        String str = "abc de";

        System.out.println(totalConsonants(str, str.length()));

    }

    }

    Python3

    def isConsonant(ch):

        ch = ch.upper()

        return not (ch == 'A' or ch == 'E' or

                    ch == 'I' or ch == 'O' or

                    ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90

    def totalConsonants(string, n):

        if n == 1:

            return isConsonant(string[0])

        return totalConsonants(string, n - 1) + isConsonant(string[n-1])

    string = "abc de"

    print(totalConsonants(string, len(string)))

    C#

    using System;

    class GFG

    {

    static Boolean isConsonant(char ch)

    {

        ch = char.ToUpper(ch);

        return (ch == 'A' || ch == 'E' ||

                ch == 'I' || ch == 'O' ||

                ch == 'U') == false &&

                ch >= 65 && ch <= 90;

    }

    static int totalConsonants(String str, int n)

    {

        if (n == 1)

        {

            if(isConsonant(str[0]))

                return 1;

            else

                return 0;

        }

        if(isConsonant(str[n - 1]))

            return totalConsonants(str, n - 1) + 1;

        else

            return totalConsonants(str, n - 1);

    }

    public static void Main(String []args)

    {

        String str = "abc de";

        Console.WriteLine(totalConsonants(str, str.Length));

    }

    }

    Javascript

    Time Complexity: O(n), where n is the length of the string
    Auxiliary Space: O(1)

    Illustration of recursive method:
     

    Count consonants in a string javascript


    How do you calculate the number of vowels and consonants in a string JavaScript?

    var userData = prompt ("Enter any text here"); var a = 0; var e = 0; var i = 0; var o = 0; var u = 0; var consonants = 0; var count; for (count = 0; count <= userData. legth; count++){ if((userData. charAt(count). match(/[aeiou]/))){ a++; e++; i++; o++; u++; }else if((userData.

    How do you count the number of consonants in a string in Java?

    To count the number of consonants in a given sentence:.
    Read a sentence from the user..
    Create a variable (count) initialize it with 0;.
    Compare each character in the sentence with the characters {'a', 'e', 'i', 'o', 'u' } If match doesn't occurs increment the count..
    Finally print count..

    How do I count strings in JavaScript?

    In JavaScript, we can count the string occurrence in a string by counting the number of times the string present in the string. JavaScript provides a function match(), which is used to generate all the occurrences of a string in an array.

    How do you count the number of vowels and consonants in a string?

    #include .
    int main().
    //Counter variable to store the count of vowels and consonant..
    int i, vCount = 0, cCount = 0;.
    char str[] = "This is a really simple sentence";.
    for(i = 0; i < strlen(str); i++){.
    str[i] = tolower(str[i]);.