JavaScript Program to Count the Occurrences of a Specific Character in a String

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 = “w3wiki” 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.

Table of Content

  • Using for loop
  • Using split() Method
  • Using match() Method
  • Using Array.reduce()

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 Beginner!";
const charToCount = "l";

console.log(
    countFrequency(text, charToCount));

Output
2

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 Beginner!";
const charToCount = "e";

console.log(
    countFrequency(text, charToCount));

Output
3

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 Beginner!";
const charToCount = "H";

console.log(
    countFrequency(text, charToCount));

Output
1

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")); 

Output
2


Contact Us