How to use match() Method In Javascript
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.
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
JavaScript Program to Count the Occurrences of a Specific Character in a String
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 = “w3wiki” 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()
Contact Us