Count a letter in a string in JavaScript
Beginner · 4 min read
How many times does the letter o appear in 'robot.dev'? Twice. Counting one character in a piece of text is a small job that shows up everywhere: counting commas in a line of a spreadsheet file, counting @ signs to spot a bad email address, or counting the dots in a file name.
In this tutorial you will write countLetter(text, letter). It counts the letter, refuses a "letter" that isn't one character, and can ignore upper and lower case when you ask it to. Then you will see two shorter ways to do the same thing and the trap hidden in one of them. You need to know loops, strings and functions.
Walking through a string
A for...of loop gives you the characters of a string one at a time:
for (const c of 'dog') console.log(c); // prints 'd', then 'o', then 'g'
To count, keep a number that starts at 0 and add 1 each time the character matches. That is the whole idea.
Options with a default
Sometimes a function needs a setting, like "ignore case". A neat way to pass settings is an options object, an object of named settings, as the last argument:
function greet(name, { loud = false } = {}) {
return loud ? name.toUpperCase() : name;
}
console.log(greet('Ada')); // 'Ada'
console.log(greet('Ada', { loud: true })); // 'ADA'
{ loud = false } reads the loud setting and uses false when it is missing. The = {} at the end means the caller can leave out the whole object.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
22 Count one letter in a string
easy('robot.dev', 'o') should give 2. Take two arguments and validate the second.
Stuck? Three hints, smallest first
- 1.
split(letter).length - 1is the shortest way, and it is a little sly. - 2. A regex needs escaping if the letter could be
.or*. - 3. Decide whether the search is case-sensitive, and say so in the name or a parameter.
Step 1: count with a loop
Start with the plainest version:
function firstTry(text, letter) {
let n = 0;
for (const c of text) if (c === letter) n++;
return n;
}
console.log(firstTry('robot.dev', 'o')); // 2
console.log(firstTry('robot.dev', 'z')); // 0
console.log(firstTry('', 'a')); // 0
A letter that isn't there gives 0, and so does an empty string. No special cases needed.
Step 2: check the second argument
What if someone passes 'ab', an empty string or the number 5? firstTry quietly returns 0, which looks like a real answer. It is better to stop with a clear error. A TypeError is the built-in error for "this value is the wrong kind of thing".
You might reach for letter.length !== 1. But some characters, like emoji, take two slots in a JavaScript string:
console.log('\u{1F600}'.length); // 2
console.log([...'\u{1F600}'].length); // 1
'\u{1F600}' is the grinning face emoji written as a code. .length counts the internal slots, while spreading the string with [...] counts real characters. So the check uses the spread version:
function checkLetter(letter) {
if (typeof letter !== 'string' || [...letter].length !== 1) {
throw new TypeError('the second argument must be a single character');
}
return 'ok';
}
console.log(checkLetter('o')); // 'ok'
console.log(checkLetter('\u{1F600}')); // 'ok'
try { checkLetter('ab'); } catch (e) { console.log(e.name); } // 'TypeError'
Step 3: add the case option
'O' and 'o' are different characters, so by default 'O' is not found in 'robot.dev'. To ignore case, lower-case both the text and the letter before comparing:
function countLetter(text, letter, { caseSensitive = true } = {}) {
if (typeof letter !== 'string' || [...letter].length !== 1) {
throw new TypeError('the second argument must be a single character');
}
const haystack = caseSensitive ? text : text.toLowerCase();
const needle = caseSensitive ? letter : letter.toLowerCase();
let n = 0;
for (const c of haystack) if (c === needle) n++;
return n;
}
console.log(countLetter('robot.dev', 'O')); // 0
console.log(countLetter('robot.dev', 'O', { caseSensitive: false })); // 2
console.log(countLetter('a\u{1F600}b\u{1F600}', '\u{1F600}')); // 2
Haystack and needle are common names for "the text you search in" and "the thing you look for". Because for...of walks real characters too, the emoji count is right.
Step 4: the split one-liner
Here is a shorter trick. Splitting a string at every o cuts it into pieces, and n matches always make n + 1 pieces:
console.log('robot.dev'.split('o')); // ['r', 'b', 't.dev']
const countBySplit = (text, letter) => text.split(letter).length - 1;
console.log(countBySplit('robot.dev', 'o')); // 2
It works, but a reader has to stop and work out why. The loop says what it means.
Step 5: the regex version, and why it needs escaping
A regular expression (regex) is a pattern for matching text. text.match(/o/g) returns every match, and g means "all of them, not just the first". You can build one from a variable with new RegExp(letter, 'g').
The trap: some characters mean something special in a pattern. A . means "any character", so searching for a dot matches everything:
console.log('a.b.c'.match(/./g).length); // 5, not 2
The fix is to escape the letter, putting a backslash before any special character so it is matched literally:
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const countByRegex = (text, letter) =>
(text.match(new RegExp(escapeRegExp(letter), 'g')) ?? []).length;
console.log(escapeRegExp('.')); // '\.'
console.log(countByRegex('a.b.c', '.')); // 2
console.log(countByRegex('abc', 'z')); // 0
match returns null when nothing matches, so ?? [] swaps that for an empty array before reading .length.
The full solution
The panel has all three versions: the loop with its check and case option, the split one-liner, and the escaped regex. It prints the example, both case settings, and the dot test that shows why escaping matters. Press Run to see the output.
// Explicit and obvious.
function countLetter(text, letter, { caseSensitive = true } = {}) {
if (typeof letter !== 'string' || [...letter].length !== 1) {
throw new TypeError('the second argument must be a single character');
}
const haystack = caseSensitive ? text : text.toLowerCase();
const needle = caseSensitive ? letter : letter.toLowerCase();
let n = 0;
for (const c of haystack) if (c === needle) n++;
return n;
}
// The one-liner. n occurrences produce n+1 pieces.
const countBySplit = (text, letter) => text.split(letter).length - 1;
// With a regex, which needs the letter escaped or '.' matches everything.
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const countByRegex = (text, letter) =>
(text.match(new RegExp(escapeRegExp(letter), 'g')) ?? []).length;
console.log("countLetter('robot.dev', 'o') =", countLetter('robot.dev', 'o'));
console.log("the question expects = 2");
console.log("case-insensitive 'O':", countLetter('robot.dev', 'O', { caseSensitive: false }));
console.log("case-sensitive 'O' :", countLetter('robot.dev', 'O'));
console.log('--- escaping matters ---');
console.log("countByRegex('a.b.c', '.') =", countByRegex('a.b.c', '.'), '<- escaped, so it counts dots');
console.log("without escaping, '.' would match every character:", ('a.b.c'.match(/./g) ?? []).length);
console.log("countBySplit('a.b.c', '.') =", countBySplit('a.b.c', '.'));
Output
17 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 17 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the example in the question", countLetter('robot.dev', 'o'), 2);
test('a letter that is not there gives 0', countLetter('robot.dev', 'z'), 0);
test('an empty string gives 0', countLetter('', 'a'), 0);
test('every character counted', countLetter('aaa', 'a'), 3);
test('it is case-sensitive by default', countLetter('robot.dev', 'O'), 0);
test('and case-insensitive on request', countLetter('robot.dev', 'O', { caseSensitive: false }), 2);
test('a dot is counted literally', countLetter('a.b.c', '.'), 2);
test('a space can be counted', countLetter('a b c', ' '), 2);
test('the split version agrees', countBySplit('robot.dev', 'o'), 2);
test('and the regex version', countByRegex('robot.dev', 'o'), 2);
test('all three agree on a dot', [countLetter('a.b.c', '.'), countBySplit('a.b.c', '.'), countByRegex('a.b.c', '.')], [2, 2, 2]);
test('without escaping, a dot would match everything', ('a.b.c'.match(/./g) ?? []).length, 5);
test('a two-character needle is refused', (() => { try { countLetter('abc', 'ab'); return 'no error'; } catch (e) { return e.constructor.name; } })(), 'TypeError');
test('an empty needle is refused', (() => { try { countLetter('abc', ''); return 'no error'; } catch (e) { return e.constructor.name; } })(), 'TypeError');
test('a non-string needle is refused', (() => { try { countLetter('abc', 5); return 'no error'; } catch (e) { return e.constructor.name; } })(), 'TypeError');
test('an emoji counts as one character', countLetter('a\u{1F600}b\u{1F600}', '\u{1F600}'), 2);
test('because for..of walks code points', [...'a\u{1F600}b'].length, 3);
Three ways, and each teaches something. split(letter).length - 1 works because n occurrences cut the string into n+1 pieces — neat, and it reads as a trick rather than as intent.
The regex version needs escapeRegExp, and the assertion showing an unescaped . matching all five characters is why. Any time you build a regex from a value you did not write, escape it; otherwise a user typing . or * changes what your pattern means.
Validating the second argument is the part the exercise title invites you to skip. A "letter" that is two characters long, empty, or not a string should be refused loudly rather than producing a plausible number. Note [...letter].length !== 1 rather than letter.length !== 1, so an emoji counts as one character — the last assertions check that for..of and spreading both walk code points.
Common mistakes
- Building a regex from user input without escaping it. A
.or*changes what the pattern means, and the count comes out wrong. - Checking
letter.length === 1. It refuses an emoji, which is one character but two slots. Use[...letter].length. - Accepting any second argument. A two-letter or empty "letter" should throw, not return a believable 0.
Try it yourself
- Count the spaces in
'a b c'. You should get 2. - Count
'O'in'Oslo or Ohio'with{ caseSensitive: false }. The answer is 5. - Make
countLetteralso throw aTypeErrorwhentextis not a string.