Count appearances of a string in another - JavaScript

We are required to write a JavaScript function that takes in two strings and returns the count of the number of times the first string appears in the second string.

Let's say our string is:

const main = 'This is the is main is string';

We have to find the appearance of the below string in the above "main" string:

const sub = 'is';

Using Regular Expression with replace()

Let's write the code for this function using a regular expression approach:

const main = 'This is the is main is string';
const sub = 'is';

const countAppearances = (main, sub) => {
    const regex = new RegExp(sub, "g");
    let count = 0;
    main.replace(regex, (a, b) => {
        count++;
    });
    return count;
};

console.log(countAppearances(main, sub));
4

Using match() Method

A simpler approach uses the match() method which returns an array of matches:

const main = 'This is the is main is string';
const sub = 'is';

const countAppearances = (main, sub) => {
    const regex = new RegExp(sub, "g");
    const matches = main.match(regex);
    return matches ? matches.length : 0;
};

console.log(countAppearances(main, sub));
4

Using split() Method

Another approach splits the string by the substring and counts the parts:

const main = 'This is the is main is string';
const sub = 'is';

const countAppearances = (main, sub) => {
    return main.split(sub).length - 1;
};

console.log(countAppearances(main, sub));
4

Handling Edge Cases

Here's a more robust version that handles empty strings and case sensitivity:

const countAppearances = (main, sub, caseSensitive = true) => {
    if (!main || !sub) return 0;
    
    const flags = caseSensitive ? 'g' : 'gi';
    const regex = new RegExp(sub.replace(/[.*+?^${}()|[\]\]/g, '\$&'), flags);
    const matches = main.match(regex);
    return matches ? matches.length : 0;
};

// Test cases
console.log(countAppearances('This is the is main is string', 'is')); // 4
console.log(countAppearances('Hello World', 'world', false)); // 1 (case insensitive)
console.log(countAppearances('', 'test')); // 0
console.log(countAppearances('test', '')); // 0
4
1
0
0

Comparison

Method Performance Readability Special Characters
replace() with RegExp Good Medium Needs escaping
match() with RegExp Good High Needs escaping
split() method Best High Handles naturally

Conclusion

The split() method provides the simplest and most efficient solution for counting substring occurrences. Use the match() method when you need regex features like case-insensitive matching.

Updated on: 2026-03-15T23:18:59+05:30

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements