JavaScript Program to Count the Occurrences of a Specific Character in a String
Last Updated :
27 May, 2024
In this article, we will see how to count the frequency of a specific character in a string with JavaScript. Counting the frequency of a specific character in a string is a common task in JavaScript.
Example:
Input : S = “geeksforgeeks” and c = ‘e’
Output : 4
Explanation: ‘e’ appears four times in str.
Input : S = “abccdefgaa” and c = ‘a’
Output : 3
Explanation: ‘a’ appears three times in str.
We will explore every approach to counting the occurrences of a specific character in a string, along with understanding their basic implementations.
Using for loop
This approach involves iterating through the string character by character using a for loop. It initializes a counter to keep track of the count of the target character.
Syntax:
for (let i = 0; i < str.length; i++) {
if (str[i] === targetChar) {
count++;
}
}
Example : This example shows the implementation of the above approach.
JavaScript
function countFrequency(
inputString,
targetChar
) {
let count = 0;
for (
let i = 0;
i < inputString.length;
i++
) {
if (
inputString[i] ===
targetChar
) {
count++;
}
}
return count;
}
const text = "Hello Geeks!";
const charToCount = "l";
console.log(
countFrequency(text, charToCount));
Using split() Method
The string is first split into an array of individual characters using the split() method. It then utilizes the filter() method to create a new array containing only the target character.
Syntax:
const charArray = str.split('');
Example : This example shows the implementation of the above approach.
JavaScript
function countFrequency(
inputString,
targetChar
) {
const stringArray =
inputString.split("");
const count = stringArray.filter(
(char) => char === targetChar
).length;
return count;
}
const text = "Hello Geeks!";
const charToCount = "e";
console.log(
countFrequency(text, charToCount));
Using match() Method
It constructs a regular expression that matches the target character globally ('g' flag) in the string. The match() method returns an array of all matches found.
Syntax:
const regex = new RegExp(targetChar,"g");
const matches = str.match(regex);
Example : This example shows the implementation of the above approach.
JavaScript
function countFrequency(
inputString,
targetChar
) {
const regexPattern = new RegExp(
targetChar,
"g"
);
const frequencyMatches =
inputString.match(regexPattern);
const counter = frequencyMatches
? frequencyMatches.length
: 0;
return counter;
}
const text = "Hello Geeks!";
const charToCount = "H";
console.log(
countFrequency(text, charToCount));
Using Array.reduce()
Using Array.reduce(), convert the string to an array of characters and accumulate the count of occurrences of the specific character by incrementing the accumulator for each occurrence found during iteration.
Example: In this example The function countOccurrences
takes a string str
and a character char
, counts occurrences of char
in str
, using the spread operator and reduce
JavaScript
function countOccurrences(str, char) {
return [...str].reduce((count, currentChar) =>
currentChar === char ? count + 1 : count, 0);
}
console.log(countOccurrences("hello world", "o"));
Similar Reads
JavaScript Program to Count the Occurrences of Each Character Here are the various methods to count the occurrences of each characterUsing JavaScript ObjectThis is the most simple and widely used approach. A plain JavaScript object (obj) stores characters as keys and their occurrences as values.JavaScriptconst count = (s) => { const obj = {}; for (const cha
3 min read
JavaScript Program to Check for Repeated Characters in a String Here are the different methods to check for repeated characters in a string using JavaScript1. Using a Frequency Counter (Object)A frequency counter is one of the most efficient ways to check for repeated characters in a string. This approach involves iterating over the string and counting how often
3 min read
JavaScript Program Count number of Equal Pairs in a String In this article, we are going to learn how can we count a number of equal pairs in a string. Counting equal pairs in a string involves finding and counting pairs of consecutive characters that are the same. This task can be useful in various applications, including pattern recognition and data analy
3 min read
JavaScript Program to Count Number of Alphabets 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: 6Explanation: Only the last 2 are not alphabets.Input: Str = "n0ji#k$"Output: 4Exp
3 min read
PHP Program to Count the Occurrence of Each Characters Given a String, the task is to count the occurrences of each character using PHP. This article explores various approaches to achieve this task using PHP, These are:Table of ContentUsing Arrays and str_split() FunctionUsing str_split() and array_count_values() FunctionsUsing preg_match_all() Functio
3 min read
Java Program to Check Whether the String Consists of Special Characters In Java, special characters refer to symbols other than letters and digits, such as @, #, !, etc. To check whether the String consists of special characters, there are multiple ways, including using the Character class, regular expressions, or simple string checks.Example:In this example, we will us
4 min read
JavaScript - How To Count String Occurrence in String? Here are the various methods to count string occurrence in a string using JavaScript.1. Using match() Method (Common Approach)The match() method is a simple and effective way to count occurrences using a regular expression. It returns an array of all matches, and the length of the array gives the co
3 min read
Count Number of Occurrences of Certain Character in String in R In this article, we will discuss how to count the number of occurrences of a certain character in String in R Programming Language. Method 1: Using the stringR package The stringR package in R is used to perform string manipulations. It needs to be explicitly installed in the working space to access
3 min read
Java Program to Count the Total Number of Vowels and Consonants in a String Given a String count the total number of vowels and consonants in this given string. Assuming String may contain only special characters, or white spaces, or a combination of all. The idea is to iterate the string and checks if that character is present in the reference string or not. If a character
2 min read
Program to count the number of characters in a word Write a program to count the number of characters in a word. Examples: Input: Word: "programming"Output: 11 Input: Word: "hello"Output: 5 Approach: To solve the problem, follow the below idea: To count the number of characters in a word, maintain a variable to count all the characters. Iterate throu
2 min read