Skip to content

charCount

Counts how many times a specific character appears in a string.

Syntax

typescript
charCount(str: string, char: string): number

Parameters

ParameterTypeDescription
strstringThe string in which to count.
charstringThe character to count (must be a single-character string).

Returns

TypeDescription
numberThe number of occurrences of the character in the string.

Example

typescript
charCount("banana", "a"); // 3
charCount("abracadabra", "b"); // 2
charCount("teste", "z"); // 0

Notes

  • Throws TypeError if str is not a string or if char is not a single-character string.
  • The count is case-sensitive.

References

Released under the MIT License.