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

As a JavaScript programmer, you may come across a scenario where you need to count the number of occurrences of a particular character in a given string.

In this tutorial, we will discuss a simple and efficient way to achieve this using JavaScript.

Let’s start by creating a function that takes two parameters, a string, and a character. The function will return the number of times the character appears in the string.

function countCharOccurrences(str, char) {
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str.charAt(i) === char) {
      count++;
    }
  }
  return count;
}

In this function, we initialize a count variable to 0. Then, we loop through the string using a for loop and check if the character at the current index is equal to the character we want to count. If it is, we increment the count variable. Finally, we return the count variable.

Let’s test our function with an example:

const str = 'Hello, World!';
const char = 'l';
const count = countCharOccurrences(str, char);

console.log(`The character "${char}" appears ${count} times in the string "${str}"`);

In this example, we are counting the number of times the letter “l” appears in the string “Hello, World!”.

The output of this program will be:

The character “l” appears 3 times in the string “Hello, World!”

That’s it! We have successfully created a JavaScript program that counts the number of occurrences of a character in a string.

In conclusion, counting the number of occurrences of a character in a string is a common task in JavaScript programming.