Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to count the occurrence of a specific string in a string in JavaScript
In JavaScript, counting occurrences of a substring within a string is a common task. There are several approaches to accomplish this, from simple loops to built-in string methods.
For example, counting how many times "is" appears in "this is a string" should return 2.
count('this is a string', 'is') should return 2;
Method 1: Using indexOf() with Loop
The most reliable approach uses indexOf() to find each occurrence and increment a counter:
const str1 = 'this is a string';
const str2 = 'is';
function countOccurrences(mainStr, subStr) {
if (subStr.length === 0) return 0;
let count = 0;
let position = 0;
while ((position = mainStr.indexOf(subStr, position)) !== -1) {
count++;
position += subStr.length; // Move past current match
}
return count;
}
console.log(countOccurrences(str1, str2));
2
Method 2: Using split() Method
Another approach splits the string by the substring and counts the resulting array length:
function countWithSplit(mainStr, subStr) {
if (subStr.length === 0) return 0;
return mainStr.split(subStr).length - 1;
}
const str1 = 'this is a string';
const str2 = 'is';
console.log(countWithSplit(str1, str2));
2
Method 3: Using Regular Expression
Regular expressions provide a flexible solution, especially for complex patterns:
function countWithRegex(mainStr, subStr) {
// Escape special regex characters
const escapedSubStr = subStr.replace(/[.*+?^${}()|[\]\]/g, '\$&');
const regex = new RegExp(escapedSubStr, 'g');
const matches = mainStr.match(regex);
return matches ? matches.length : 0;
}
const str1 = 'this is a string';
const str2 = 'is';
console.log(countWithRegex(str1, str2));
2
Handling Overlapping Occurrences
For overlapping matches (like "aa" in "aaa"), modify the position increment:
function countOverlapping(mainStr, subStr) {
if (subStr.length === 0) return 0;
let count = 0;
let position = 0;
while ((position = mainStr.indexOf(subStr, position)) !== -1) {
count++;
position += 1; // Move by 1 for overlapping matches
}
return count;
}
console.log(countOverlapping('aaa', 'aa')); // Non-overlapping: 1, Overlapping: 2
2
Comparison
| Method | Performance | Overlapping Support | Complexity |
|---|---|---|---|
| indexOf() Loop | Fast | Yes (configurable) | Medium |
| split() | Fast | No | Low |
| Regular Expression | Slower | No (by default) | High |
Conclusion
The indexOf() method with a loop provides the most control and performance for counting substring occurrences. Use split() for simple cases, and regular expressions when pattern matching is needed.
