Back to JavaScript
2025-12-075 min read

JavaScript Program to Check the Number of Occurrences of a Character in the String

Learn JavaScript Program to Check the Number of Occurrences of a Character in the String step by step with clear examples and exercises.

Title: JavaScript Program to Check the Number of Occurrences of a Character in the String

Why This Matters

In programming, it is often necessary to find the frequency or count of specific characters within a string. This skill comes in handy when dealing with text processing tasks like data validation, text analysis, and more. In this lesson, we will learn how to write a JavaScript program that counts the occurrences of a given character in a string using various methods.

Prerequisites

Before diving into the core concept, it is essential to have a good understanding of the following topics:

  • Basic JavaScript syntax and data types (variables, strings, operators)
  • Control structures (if statements, loops)
  • Understanding of arrays and array methods like push(), pop(), and indexOf()

Importance of Prerequisites

Familiarity with the prerequisites will help you understand the concepts presented in this lesson more easily. If you are not confident in any of these areas, consider reviewing them before proceeding.

Core Concept

Using a For Loop

One way to count the occurrences of a character in a string is by using a for loop. This method involves iterating through each character of the string and comparing it with the target character. If there's a match, we increment a counter variable. Here's an example:

function countChar(str, char) {
let frequency = {};
for (let i = 0; i < str.length; i++) {
if (!frequency[str[i]]) {
frequency[str[i]] = 1;
} else {
frequency[str[i]]++;
}
if (str[i] === char) {
console.log(`Character found at index ${i}`);
}
}
return frequency[char];
}

In this example, the countChar function takes a string and a character as arguments. It initializes an empty object called frequency, which will be used to store the counts of each character in the input string. Then, it loops through each character of the input string using a for loop. If the current character is not already in the frequency object, it is added with a count of 1. If the current character is already in the frequency object, its count is incremented by 1. The function also checks if the current character matches the target character and logs its index if there's a match. Finally, the function returns the count of the target character.

Using String Methods

JavaScript provides built-in methods to work with strings, making it easier to find the occurrences of a specific character. One such method is split(), which splits a string into an array of substrings based on a specified delimiter. Here's an example using this method:

function countChar(str, char) {
let frequency = {};
str.split('').forEach((char) => {
if (!frequency[char]) {
frequency[char] = 1;
} else {
frequency[char]++;
}
});
return frequency[char];
}

In this example, we use the split() method to convert the input string into an array of characters. Then, we loop through each character using forEach(), incrementing the count in the frequency object for each occurrence of the target character. Finally, the function returns the count of the target character.

Using Regular Expressions

Regular expressions (regex) provide a powerful way to search and manipulate strings in JavaScript. We can use them to find all instances of a specific pattern and count their occurrences in a string. Here's an example using regex:

function countChar(str, char) {
let regex = new RegExp(char, 'g');
return (str.match(regex) || []).length;
}

In this example, we create a regular expression object regex that matches the target character. The match() method returns an array of all matches in the string, and we count their length to get the total number of occurrences.

Worked Example

Let's count the number of 'o' occurrences in the following string: "school."

function countChar(str, char) {
let frequency = {};
str.split('').forEach((char) => {
if (!frequency[char]) {
frequency[char] = 1;
} else {
frequency[char]++;
}
});
return frequency['o'];
}

const str = "school.";
console.log(countChar(str, 'o')); // Output: 2

In this example, we define the countChar function and call it with the input string and target character. The output is 2 since there are two 'o' characters in the string.

Common Mistakes

  1. Forgetting to initialize the frequency object:
function countChar(str, char) {
let frequency = ; // NOT initialized
str.split('').forEach((char) => {
if (!frequency[char]) {
frequency[char] = 1;
} else {
frequency[char]++;
}
});
return frequency[char];
}
  1. Not using the correct regular expression syntax:
function countChar(str, char) {
let regex = new RegExp(char); // Incorrect syntax for case-insensitive search
return (str.match(regex, 'g')) || []).length;
}
  1. Not handling empty strings or strings without the target character:
function countChar(str, char) {
let frequency = {};
str.split('').forEach((char) => {
if (!frequency[char]) {
frequency[char] = 1;
} else {
frequency[char]++;
}
});
if (frequency[char]) {
return frequency[char];
} else {
console.log(`${char} not found in the string`);
return 0;
}
}

Practice Questions

  1. Write a JavaScript function to count the number of vowels in a string using a for loop and an array of vowels (a, e, i, o, u).
  2. Modify the countChar() function to accept an optional parameter called caseSensitive, which determines whether the search should be case-sensitive or not.
  3. Write a function that counts the occurrences of two characters in a string simultaneously using regular expressions.
  4. Write a function that checks if a given character appears more frequently than another character in a string.
  5. Write a function that replaces all instances of a specified character with another character in a string.

FAQ

Q: Why use split() instead of a for loop to count character occurrences?

A: Using split() can be more efficient when dealing with long strings since it only creates an array once, while a for loop checks every character in the string. However, both methods have their use cases depending on the specific requirements of your program.

Q: How to count the number of occurrences of multiple characters in a string?

A: You can create an array to store the counts of each character and iterate through the string using a for loop or indexOf(). Alternatively, you can use regular expressions to find all instances of a specific pattern.

Q: Can I count the occurrences of a character in a string without using loops or built-in methods?

A: While it's possible to write custom functions to count character occurrences without using loops or built-in methods, it would be less efficient and more complex than utilizing JavaScript's provided functionality. It is generally recommended to use the built-in methods for simplicity and performance.

JavaScript Program to Check the Number of Occurrences of a Character in the String | JavaScript | XQA Learn