Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Count a Character

Data Structures, Operators & Stringsmedium

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 128: Working With Strings - Part 1

Implement `countChar(s, ch)` returning how many times the single character `ch` appears in `s`.

Sample tests

Input: countChar("banana", "a")
Output: 3
Input: countChar("banana", "x")
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Passing a multi-character needle when only single characters are expected.

Learning resources

  • MDN: String
Approach & explanation (try first)

Iterating once and incrementing on each match counts occurrences of the character.

Loading...
⌘/Ctrl + Enter

Run your code to see results.