How do you count occurrences of a specific character in a JavaScript string? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you count occurrences of a specific character in a JavaScript string?

message-square
0

To count occurrences of a specific character in a JavaScript string, iterate over the string with a for...of loop (or split(char).length - 1 for a single fixed code unit / literal substring) while validating that both the source string and target character are strings and that the target is a single character (handling Unicode surrogate pairs / emoji properly via code points rather than raw UTF-16 code units when full-character accuracy matters).


1. Counting Characters Safely with a for...of Loop

Use a for...of loop over the string and increment a counter whenever ch === targetChar—this iterates over Unicode code points cleanly (so surrogate pairs like emojis are not split mid-pair) and avoids allocating an array of substrings:

// Count occurrences of a single character in a string using a for...of loop
function countCharOccurrences(source, targetChar) {
  if (typeof source !== "string") {
    throw new TypeError("Expected source to be a string.");
  }
  if (typeof targetChar !== "string") {
    throw new TypeError("Expected targetChar to be a string.");
  }

  const targetChars = [...targetChar];
  if (targetChars.length !== 1) {
    throw new RangeError("Expected targetChar to be a single character.");
  }

  const needle = targetChars[0];

  try {
    let count = 0;
    for (const ch of source) {
      if (ch === needle) {
        count += 1;
      }
    }
    return count;
  } catch (error) {
    throw new Error(`Failed to count character occurrences: ${error.message}`);
  }
}

// Example usage:
try {
  console.log(countCharOccurrences("banana", "a"));           // 3
  console.log(countCharOccurrences("a,b,c,d", ","));        // 3
  console.log(countCharOccurrences("🚀-go-🚀-now", "🚀"));  // 2
} catch (error) {
  console.error(`${error.name}:${error.message}`);
}
  • Validate targetChar length ([...targetChar].length === 1): Prevents subtle bugs where passing "" or a multi-character string returns misleading counts.
  • Prefer for...of over .split(char).length - 1 for large strings or Unicode pairs: .split() creates a new array of substrings and operates on UTF-16 code units rather than Unicode code points.

2. Case-Insensitive Counting and Index Tracking with a Map

When counting letters case-insensitively or tracking character frequency / match positions across a string, normalize case explicitly and use a Map rather than a plain object to avoid prototype-key collisions (such as "constructor" or "toString"):

// Count character occurrences optionally case-insensitively and record match indices
function inspectCharMatches(source, targetChar, { caseInsensitive = false } = {}) {
  if (typeof source !== "string") {
    throw new TypeError("Expected source to be a string.");
  }
  if (typeof targetChar !== "string" || [...targetChar].length !== 1) {
    throw new RangeError("Expected targetChar to be a single character.");
  }
  if (typeof caseInsensitive !== "boolean") {
    throw new TypeError("Expected caseInsensitive to be a boolean.");
  }

  try {
    const normalizedSource = caseInsensitive ? source.toLowerCase() : source;
    const normalizedTarget = caseInsensitive ? targetChar.toLowerCase() : targetChar;

    const stats = new Map([
      ["count", 0],
      ["indices", []]
    ]);
    const indices = stats.get("indices");

    let index = 0;
    for (const ch of normalizedSource) {
      if (ch === normalizedTarget) {
        stats.set("count", stats.get("count") + 1);
        indices.push(index);
      }
      index += 1;
    }

    return stats;
  } catch (error) {
    throw new Error(`Failed inspecting character matches: ${error.message}`); } }  // Example usage: try { const result = inspectCharMatches("Mississippi", "s", { caseInsensitive: true }); console.log("Count:", result.get("count"));     // 4 console.log("Indices:", result.get("indices")); // [2, 3, 5, 6] } catch (error) { console.error(`${error.name}: ${error.message}`); }  - **Use `Map` for dynamic lookup/metric keys:** Avoids collisions with `Object.prototype` keys when aggregating arbitrary characters from untrusted input. - **Be careful with locale-specific casing (`toLocaleLowerCase` vs. `toLowerCase`):** Choose locale-aware casing only when user-facing text rules require it.  ---  ## 3. Regex Pitfalls and Escaping Special Characters  If using regular expressions (`matchAll()`), **escape regex metacharacters** (`$`, `.`, `*`, `+`, `?`, `(`, `)`, `[`, `]`, `{`, `}`, `^`, `\`, `|`) first—otherwise passing `"."` or `"+"` as an unescaped pattern changes the meaning of the regex:

// Escape special regex characters before building a dynamic character matcher
function escapeRegexLiteral(literal) {
  if (typeof literal !== "string") {
    throw new TypeError("Expected literal to be a string.");
  }
  return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

// Count matches safely using an escaped global regex
function countCharWithRegex(source, targetChar) {
  if (typeof source !== "string") {
    throw new TypeError("Expected source to be a string.");
  }
  if (typeof targetChar !== "string" || [...targetChar].length !== 1) {
    throw new RangeError("Expected targetChar to be a single character.");
  }

  try {
    const escaped = escapeRegexLiteral(targetChar);
    const regex = new RegExp(escaped, "gu");
    const matches = source.match(regex);
    return matches ? matches.length : 0;
  } catch (error) {
    throw new Error(`Regex character count failed: ${error.message}`);
  }
}

// Example usage:
try {
  console.log(countCharWithRegex("1.2.3.4", ".")); // 3 (literal dots, not any char)
  console.log(countCharWithRegex("a+b+c", "+"));   // 2 (literal plus signs)
} catch (error) {
  console.error(`${error.name}:${error.message}`);
}
  • Always escape metacharacters before new RegExp(...): Unescaped "." matches every character rather than a literal period.
  • Avoid stateful /g regex instances stored across calls: Creating a fresh RegExp per call prevents lastIndex bugs across invocations.