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.
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
Contact Us