Exercise 13: Count Occurrences of Substring

Problem Statement

Function `countOccurrences(str, substr)` banao jo string me substring ki count return kare. Example: countOccurrences("hello hello", "hello") => 2

Sample Output:

countOccurrences("hello hello", "hello") => 2
countOccurrences("aaa", "aa") => 2

Solution

const countOccurrences = (str, substr) => {
  const s = String(str ?? ""), sub = String(substr ?? "");
  if (sub.length === 0) return 0;
  return (s.match(new RegExp(sub.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g")) || []).length;
};

Explanation

Overall Goal:

  • String me substring ki frequency count karna.

Real world:

  • Text analysis: pattern counting.
  • Search: occurrence counting.