How to Count Consonants in a String in JavaScript?

You need to analyze code and count consonants in a string using JavaScript, but you don’t know how?

Well, don’t worry! It is because we will guide you on how to do it accurately.

This article will show several approaches to help you to count consonants in a string in JavaScript.

What is consonant in a string?

Consonants are defined as English alphabet characters that are not vowels (a, e, i, o, and u).

Examples of consonants includes b, c, d, f, g and so on.

Solutions on how to count consonants in a string in JavaScript

To count the number of consonants in a string in JavaScript. You can use the provided solutions below.

There are different methods available to help us achieve this.

So without further ado. Let’s explore a few approaches.

Solution 1: Use for loop

To calculate the count of consonants in a string, utilize the “for” loop.

In JavaScript, this looping mechanism provides a reliable and efficient way to execute a block of code repeatedly, contingent upon a specified condition.

Using the “for” loop, you can effectively iterate through the characters of a string and identify consonants to determine their total count.

Here’s an example:

function consonants(str) {
  var countConsonants = 0;

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

    if (str[i] !== "a" && str[i] !== "e" && str[i] !== "i" &&
      str[i] !== "o" && str[i] !== "u" && str[i] !== " ") {
      countConsonants++;
    }
  }
  return (countConsonants);
}
console.log(consonants("Itsourcecode"));

The provided function accepts a string as an argument and calculates the count of consonants within the string.

It achieves this by iteratively examining each character in the string using a “for” loop, and employing conditional statements to verify if the character is neither a vowel nor a space.

Output:

7

NOTE: The countConsonants function provided in the previous example above only counts lowercase consonants.

If you want to count both uppercase and lowercase consonants, you can modify the function to consider the case-insensitivity of the characters.

Here’s an example of how you can do this:

function countConsonants(str) {
  let consonantCount = 0;
  for (let i = 0; i < str.length; i++) {
    let char = str.charAt(i).toLowerCase();
    if (char !== "a" && char !== "e" && char !== "i" && char !== "o" && char !== "u" && char !== " ") {
      consonantCount++;
    }
  }
  return consonantCount;
}

let sampleString = "Itsourcecode";
let result = countConsonants(sampleString);
console.log(`The number of consonants in "${sampleString}" is ${result}.`);

Output:

The number of consonants in "Itsourcecode" is 6.

Solution 2: Use regular expressions and the match method

To count consonants in a string in JavaScript, you can use regular expression.

Here’s an example:

function countConsonants(str) {
  let matches = str.match(/[^aeiou\s]/gi);
  return matches ? matches.length : 0;
}

let sampleString = "Itsourcecode";
let result = countConsonants(sampleString);
console.log(`The number of consonants in "${sampleString}" is ${result}.`);

The provided function accepts a string as input and calculates the count of consonants within that string.

This is accomplished by utilizing a regular expression that matches any characters in the string that are neither vowels nor whitespace.

By using the match method, which returns an array of all matches, we can determine the number of consonants by checking the length of this array.

Output:

The number of consonants in "Itsourcecode" is 6.

Solution 3: Use split and filter methods

You can also use the split and filter methods to count consonants in a string.

This solution converts the string into an array of individual characters using the split method.

Then, we used the filter method, that selects only the characters that are not vowels or whitespace.

Here’s an example:

function countConsonants(str) {
  return str.split('').filter(e => e.match(/[^aeiou\s]/i)).length;
}

let sampleString = "Itsourcecode";
let result = countConsonants(sampleString);
console.log(`The number of consonants in "${sampleString}" is ${result}.`);

Output:

The number of consonants in "Itsourcecode" is 6.

Solution 4: Use the reduce method

Lastly, you can use the reduce method to to count the consonant in string in JavaScript.

Here’s an example:

function countConsonants(str) {
  return str.split('').reduce((acc, char) => {
    if (char.match(/[^aeiou\s]/i)) {
      acc++;
    }
    return acc;
  }, 0);
}

let sampleString = "Itsourcecode";
let result = countConsonants(sampleString);
console.log(`The number of consonants in "${sampleString}" is ${result}.`);

In this solution, we first split the string into an array of characters. Then, we use the reduce method to iterate through the array and count the number of consonants.

For each character, we check if it is not a vowel or whitespace, and if so, we increment the count. Finally, we obtain the total count of consonants.

Output:

The number of consonants in "Itsourcecode" is 6.

How to count count vowel and consonants in a string in JavaScript?

To get count the count the vowels and consonants in a string in JavaScript, you can use the following code:

function countVowelsAndConsonants(str) {
  let vowelCount = 0;
  let consonantCount = 0;
  for (let i = 0; i < str.length; i++) {
    if (str.charAt(i).match(/[aeiou]/i)) {
      vowelCount++;
    } else if (str.charAt(i).match(/[^aeiou\s]/i)) {
      consonantCount++;
    }
  }
  return {vowels: vowelCount, consonants: consonantCount};
}

let sampleString = "Itsourcecode";
let result = countVowelsAndConsonants(sampleString);
console.log(`The number of vowels in "${sampleString}" is ${result.vowels}.`);
console.log(`The number of consonants in "${sampleString}" is ${result.consonants}.`);

The provided code defines a function called countVowelsAndConsonants. This function takes a string as input and returns an object with the counts of vowels and consonants.

It works by looping through each character in the string and checking if it is a vowel or consonant using regular expressions. If a character is found to be a vowel, the function increments the vowelCount variable.

If it is determined to be a consonant, the consonantCount variable is incremented.

Output:

The number of vowels in "Itsourcecode" is 6.
The number of consonants in "Itsourcecode" is 6.

As you have seen in the output, the function returns an object containing the vowelCount and consonantCount values.

Conclusion

In conclusion, this article provides several solutions to count consonants in a string using JavaScript.

It covers four approaches along with example code for each solution, including the use of a for loop, regular expressions with the match method, the split and filter methods, and the reduce method.

The article also mentions how to count both vowels and consonants in a string in JavaScript.

The solutions that we provide in different ways to accurately count consonants in JavaScript can be adapted for uppercase and lowercase consonants.

We are hoping that this article provides you with enough information that helps you understand the count consonants in a string JavaScript.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment