JavaScript Program to Count Number of Alphabets
Last Updated :
13 Sep, 2023
In this article, we are going to implement an algorithm by which we can count the number of alphabets present in a given string. A string can consist of numbers, special characters, or alphabets.
Examples:
Input: Str = "adjfjh23"
Output: 6
Explanation: Only the last 2 are not alphabets.
Input: Str = "n0ji#k$"
Output: 4
Explanation: 0, #, and $ are not alphabets.
In this article, we are going to implement it with two different approaches.
Approach 1: Using RegExp
In this approach, we will use Regular Expression to count the number of alphabets in a string. A regular expression is a sequence of characters that forms a search pattern. The a-zA-Z pattern finds any character between the brackets a to z and A to Z.
Syntax:
/pattern/modifiers;
Example:
Javascript
let str = "Geeks123for#$Geeks" ;
let regex = /[a-zA-Z]/g;
console.log(str.match(regex).length);
|
Approach 2: Using for Loop
In this approach, we will use for loop to traverse each character of a string, and use str.charAt() method to check the character value between ‘A’ to ‘Z’.
Syntax:
for (statement 1 ; statement 2 ; statement 3){
code here...
}
Example:
Javascript
let str = "geeks12354forgeeks" ;
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) >= 'A' || str.charAt(i) >= 'Z' ) {
count++;
}
}
console.log(count);
|
Share your thoughts in the comments
Please Login to comment...