Count ASCII capitals
Difficulty: Easy
Try your first run
No account is needed to try this exercise. Write your answer, run the tests, and use the feedback to improve it.
- Read the examples and the required return value.
- Edit the supplied function in the editor, keeping its name and parameters. Return your answer, then select Run code.
- Use the test feedback to try again. Hints are available without replacing your code.
Return how many characters are ASCII uppercase letters A through Z. Ignore lowercase letters, punctuation, digits, emoji, and non-ASCII uppercase letters.
Examples
""0"JS and HTML"6"abc"0Constraints
0–10,000 UTF-16 code units. Do not use locale-dependent casing to decide whether a character counts.
Review lesson: Slicing, searching, and replacementA little nudge
Reveal one hint at a time. Give yourself a moment to try it.
- The contract names an exact interval of characters.
- Compare each character with A and Z.
- Increment a counter only when both bounds hold.
Worked solution
Try your own approach first, then compare the reasoning.
function countCapitals(text) {
let count = 0;
for (const ch of text) if (ch >= "A" && ch <= "Z") count++;
return count;
}
Explicit bounds match the ASCII contract. Comparing a character with its uppercased version would count digits and punctuation too, because many such characters are unchanged by casing.
Complexity
O(n) time and O(1) auxiliary space.
Ready when you are
Write your solution, then run it against the practice tests.
Press Esc, then Tab to leave the editor. Code runs in an isolated browser workspace. Tests support learning, not verified grading.