Count Number Of Character Occurrences In A String Using JavaScript

In this article, I will demonstrate various ways to count the number of character occurrences in a string using javascript. I will create different code examples for all three approaches.

  1. Using a loop
  2. Using regular expressions
  3. Using the split function and the length property.

Let's start with the first approach,

1. Using a loop

To count the number of occurrences of a specific character in the string using a for loop, we can iterate over each character and check for a specific character inside the loop. If it matches that character, the count will increase. Let's take an example code snippet.

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

Usage of code example,

let str = "C-sharp Corner";
let char = "r";
let count = countOccurrencesOfcharacterinString(str, char);
console.log(`The character '${char}' Found ${count} times in the string '${str}'.`);

The output is,

The character 'r' found 3 times in the string 'hello world'.

2. Using regular expression

Another way to achieve the same result is by using regular expressions in JavaScript. Please find an example code snippet with regular expressions:

function countOccurrencesOfcharacterinString(str, char) {
  const regex = new RegExp(char, "g");
  const count = (str.match(regex) || []).length;
  return count;
}

Usage of code example

const str = "csharp corner is the best community for .net developer";
const char = "r";
const count = countOccurrencesOfcharacterinString(str, char);
console.log(`The character "${char}" found ${count} times in "${str}".`);

The output of this example

The character "r" found 5 times in "csharp corner is the best community for .net developer".

3. Using the split() method and the length property

One more way is to use the split() method and the length property to find the number of occurrences without using a loop. Here is an example using split() and the length property.

function countOccurrencesOfcharacterinString(str, char) {
  const count = str.split(char).length - 1;
  return count;
}

Usage of code example

const str = "c-sharp corner developer community";
const char = "r";
const count = countOccurrencesOfcharacterinString(str, char);
console.log(`The character "${char}" found ${count} times in "${str}".`);

The output of this example,

The character "r" found 4 times in "c-sharp corner developer community"

Summary

In this article, I have demonstrated various ways to find the number of character occurrences in a given string. There are multiple ways to achieve this, like using a loop, a regular expression, the split function, or the length property.

Here is my other article on Javascript if you wish to read it: Difference Between =, == And === In JavaScript