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 😊.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment