Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

countOccurrences

Counts how many times a substring appears in a string.

TypeScript
Copied!
1/**
2 * Counts how many times a substring appears in a string.
3 *
4 * @param str - The string to search within.
5 * @param subStr - The substring to count.
6 * @returns Number of non-overlapping occurrences of the substring.
7 *
8 * @throws Error if subStr is an empty string.
9 */
10export function countOccurrences(str: string, subStr: string): number {
11  if (subStr === '') {
12    throw new Error('Substring cannot be an empty string');
13  }
14
15  return str.split(subStr).length - 1;
16}
  • Straightforward Logic

    Uses native .split() method for clear and concise counting of non-overlapping substring matches.

  • Performs Well for Most Use Cases

    Efficient for typical strings due to simple string operations and no need for manual looping or regex.

  • Error Handling for Invalid Input

    Explicitly throws an error for an empty substring, preventing silent or unintended behavior.

  • Language-Agnostic

    Works with any string regardless of alphabet, casing, or language since it doesn’t rely on locale-specific rules.

Tests | Examples

TypeScript
Copied!
1test('countOccurrences - basic usage', () => {
2  expect(countOccurrences('banana', 'na')).toBe(2);
3});
4
5test('countOccurrences - no matches', () => {
6  expect(countOccurrences('hello world', 'xyz')).toBe(0);
7});
8
9test('countOccurrences - full match', () => {
10  expect(countOccurrences('aaa', 'a')).toBe(3);
11});
12
13test('countOccurrences - special characters', () => {
14  expect(countOccurrences('a*b*c*', '*')).toBe(3);
15});
16
17test('countOccurrences - empty substring throws', () => {
18  expect(() => countOccurrences('abc', '')).toThrow('Substring cannot be an empty string');
19});

Common Use Cases

  • Text Analysis

    Count the number of keywords, symbols, or tags in user input, articles, or logs.

  • Form Validation

    Check how often a delimiter or special token appears in input fields (e.g., commas in email lists).

  • Search/Highlight Features

    Determine how many matches to highlight in a UI component like search results.

  • Data Cleaning

    Identify repeated patterns, errors, or anomalies in user-entered data.

  • Metrics & Logging

    Analyze frequency of specific terms or codes in error logs, chat transcripts, or output files.

Codebase: Utilities -> Strings -> countOccurrences | Yevhen Klymentiev