Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to Count the Occurrences of a Specific Character in a String
Next article icon

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

Last Updated : 27 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = “geeksforgeeks” 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 Geeks!"; 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 Geeks!"; 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 Geeks!"; 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 

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

A

anjugaeu01
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Program
  • Geeks Premier League 2023

Similar Reads

    JavaScript Program to Count the Occurrences of Each Character
    Here are the various methods to count the occurrences of each characterUsing JavaScript ObjectThis is the most simple and widely used approach. A plain JavaScript object (obj) stores characters as keys and their occurrences as values.JavaScriptconst count = (s) => { const obj = {}; for (const cha
    3 min read
    JavaScript Program to Check for Repeated Characters in a String
    Here are the different methods to check for repeated characters in a string using JavaScript1. Using a Frequency Counter (Object)A frequency counter is one of the most efficient ways to check for repeated characters in a string. This approach involves iterating over the string and counting how often
    3 min read
    JavaScript Program Count number of Equal Pairs in a String
    In this article, we are going to learn how can we count a number of equal pairs in a string. Counting equal pairs in a string involves finding and counting pairs of consecutive characters that are the same. This task can be useful in various applications, including pattern recognition and data analy
    3 min read
    JavaScript Program to Count Number of Alphabets
    We are going to implement an algorithm by which we can count the number of alphabets present in a given string. A string can consist of numbers, special characters, or alphabets.Examples:Input: Str = "adjfjh23"Output: 6Explanation: Only the last 2 are not alphabets.Input: Str = "n0ji#k$"Output: 4Exp
    3 min read
    PHP Program to Count the Occurrence of Each Characters
    Given a String, the task is to count the occurrences of each character using PHP. This article explores various approaches to achieve this task using PHP, These are:Table of ContentUsing Arrays and str_split() FunctionUsing str_split() and array_count_values() FunctionsUsing preg_match_all() Functio
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences