JavaScript - How To Count String Occurrence in String?
Last Updated :
27 Nov, 2024
Here are the various methods to count string occurrence in a string using JavaScript.
1. Using match() Method (Common Approach)
The match() method is a simple and effective way to count occurrences using a regular expression. It returns an array of all matches, and the length of the array gives the count.
JavaScript
const s1 = "hello world, hello JavaScript!";
const s2 = "hello";
const count = (s1.match(new RegExp(s2, "g")) || []).length;
console.log(count);
- new RegExp(word, "g"): Creates a global regular expression for the target word.
- match(): Returns an array of matches.
- || []: Handles cases where no matches are found (returns an empty array).
2. Using while Loop
You can manually iterate through the string to count occurrences by checking for the substring at each position.
JavaScript
const s1 = "hello world, hello JavaScript!";
const s2 = "hello";
let count = 0;
let pos = 0;
while ((pos = s1.indexOf(s2, pos)) !== -1) {
count++;
// Move past the current match
pos += s2.length;
}
console.log(count);
- indexOf(s2, pos): Finds the position of the substring starting from pos.
- pos += s2.length: Advances the position to avoid counting overlapping matches.
3. Using split() Function
By splitting the string at each occurrence of the target substring, the resulting array.length-1 will give the count.
JavaScript
const s1 = "hello world, hello JavaScript!";
const s2 = "hello";
const count = s1.split(s2).length - 1;
console.log(count);
- split(word): Splits the string at every occurrence of the substring.
- length - 1: The number of occurrences equals the number of splits minus one.
4. Using indexOf() in a Loop
Another approach using indexOf() involves repeatedly searching for the substring.
JavaScript
const s1 = "hello world, hello JavaScript!";
const s2 = "hello";
let count = 0;
let pos = s1.indexOf(s2);
while (pos !== -1) {
count++;
pos = s1.indexOf(s2, pos + s2.length);
}
console.log(count);
- indexOf(word, start): Finds the substring starting from the specified index.
- The loop continues until indexOf() returns -1 (no more matches).
5. Using Regular Expressions
Regular expressions offer a concise and powerful way to count substring occurrences.
JavaScript
const s1 = "hello world, hello JavaScript!";
const s2 = "hello";
const regex = new RegExp(s2, "g");
const count = (s1.match(regex) || []).length;
console.log(count);
- RegExp(word, "g"): Enables global matching of the substring.
- match(): Returns all matches as an array.
6. Using reduce() Method
You can use reduce() to iterate through an array representation of the string (e.g., split by spaces) and count matches.
JavaScript
const s1 = "hello world, hello JavaScript!";
const s2 = "hello";
const count = s1.split(" ")
.reduce((acc, curr) =>
(curr === s2 ? acc + 1 : acc), 0);
console.log(count);
- split(" "): Breaks the string into an array of words.
- reduce(): Accumulates the count by comparing each element with the target word.
7. Using includes() and slice() Methods
You can use includes() to check for the substring and slice() to move past each match.
JavaScript
const s1 = "hello world, hello JavaScript!";
const s2 = "hello";
let count = 0;
let temp = s1;
while (temp.includes(s2)) {
count++;
temp = temp.slice(temp.indexOf(s2) + s2.length);
}
console.log(count);
- includes(word): Checks if the substring exists in the string.
- slice(): Creates a new substring starting after the current match.
Which Method To Choose?
- The match() method with a global regular expression is the most efficient and widely used method for counting substring occurrences.
- For specific cases, such as overlapping matches or advanced patterns, regular expressions provide flexibility.
- Approaches like split() and loops with indexOf() are clear and concise alternatives, especially for simple substring counting. Choose the method that best fits your needs based on the input and complexity!
Similar Reads
JavaScript - How to Count Words of a String? Here are the various methods to count words of a string in JavaScript.1. Using split() MethodThe simplest and most common approach is to use the split() method to divide the string into an array of words and count the length of the array.JavaScriptconst count = (s) => s.trim().split(/\s+/).length
3 min read
PHP Find the number of sub-string occurrences We are given two strings s1 and s2. We need to find the number of occurrences of s2 in s1. Examples: Input : $s1 = "geeksforgeeks", $s2 = "geeks" Output : 2 Explanation : s2 appears 2 times in s1 Input : $s1 = "Hello Shubham. how are you?"; $s2 = "shubham" Output : 0 Explanation : Note the first let
2 min read
CSES solution - Counting Patterns Given a string S and patterns[], count for each pattern the number of positions where it appears in the string. Examples: Input: S = "aybabtu", patterns[] = {"bab", "abc", "a"}Output: 102Explanation: "bab" occurs only 1 time in "aybabtu", that is from S[2...4]."bab" does not occur in "aybabtu"."a" o
15 min read
PHP substr_count() Function The substr_count() is a built-in function in PHP and is used to count the number of times a substring occurs in a given string. The function also provides us with an option to search for the given substring in a given range of the index. It is case sensitive, i.e., "abc" substring is not present in
3 min read
PHP mb_substr_count() Function The  mb_substr_count() function is an inbuilt function in PHP that counts the occurrence of strings within a given string. Syntax: mb_substr_count($haystack, $needle, $encoding): intParameters: This function accepts three parameters that are described below: $haystack: This is the main parameter wh
1 min read