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

To understand this example, you should have the knowledge of the following JavaScript programming topics:


If you check the number of occurrences of 'o' in the string 'school', the result is 2.

Example 1: Check Occurrence of a Character Using for Loop

Output

Enter a string: school
Enter a  letter to check: o
2

In the above example, the user is prompted to enter a string and the character to check.

  • In the beginning, the value of the count variable is 0.
  • The for loop is used to iterate over the strings.
  • The charAt() method returns a character at a specified index.
  • During each iteration, if the character at that index matches the required character to match, then the count variable is increased by 1.

Example 2: Check occurrence of a character using a Regex

Output

Enter a string: school
Enter a  letter to check: o
2

In the above example, a regular expression (regex) is used to find the occurrence of a string.

  • const re = new RegExp(letter, 'g'); creates a regular expression.
  • The match() method returns an array containing all the matches. Here, str.match(re);gives ["o", "o"].
  • The length property gives the length of an array element.