Check if a string is an isogram in JavaScript
Intermediate · 4 min read
An isogram is a word where no letter appears twice. lumberjack is one: every letter is different. lagos state is not, because a, s and t all repeat. Word games use this rule, and the same check, "are all of these different?", turns up everywhere in real code: unique usernames, unique IDs, no duplicate seats in a booking.
In this tutorial you will write isIsogram, which answers yes or no, and firstRepeat, which tells you which letter spoiled the word. You should know what toLowerCase does and how a simple for...of loop works. Everything else is explained below.
The trick: a Set forgets duplicates
A Set is a collection that keeps each value only once. If you add the same value twice, the second one is ignored. You can build a Set straight from a string, and it walks the string one character at a time:
console.log(new Set('abba').size); // 2
console.log('abba'.length); // 4
The Set kept only a and b, so its size is 2. The string still has all four characters. That gap is the whole idea: if the Set is smaller than the string, something was repeated.
Cleaning the text first
The exercise says to ignore case, spaces and hyphens. A and a should count as the same letter, and the space in lagos state is not a letter at all. So before comparing, we lowercase the text and remove everything that is not a letter from a to z.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
42 Is it an isogram?
fairAn isogram has no repeated letters. Check 'lumberjack' and 'lagos state', ignoring case, spaces and hyphens.
Stuck? Three hints, smallest first
- 1. A
Setdrops duplicates, so compare its size against the length. - 2. Strip everything that is not a letter before counting.
- 3. Decide whether a repeated digit should disqualify the word, and say so in the code.
Step 1: keep only the letters
const text = 'Six-Year-Old';
const letters = text.toLowerCase().replace(/[^a-z]/g, '');
console.log(letters); // 'sixyearold'
/[^a-z]/g is a regular expression, a small pattern for matching text. [a-z] means "any letter from a to z", and the ^ inside the brackets flips it to "anything that is not one of those". The g flag means "every match, not just the first". Replacing every match with '' deletes it.
Lowercasing comes first. If you removed non-letters first, the capital S, Y and O would be deleted along with the hyphens.
Step 2: compare the Set with the length
const isIsogram = (text) => {
const letters = text.toLowerCase().replace(/[^a-z]/g, '');
return new Set(letters).size === letters.length;
};
console.log(isIsogram('lumberjack')); // true
console.log(isIsogram('lagos state')); // false
console.log(isIsogram('six-year-old')); // true
console.log(isIsogram('Abba')); // false
If no letter repeats, the Set keeps every letter and its size equals the length. One repeat makes the Set smaller. Abba is caught because lowercasing turned both A and a into a.
Step 3: the natural wrong turn
It is tempting to skip the cleaning and compare the raw text:
const naive = (text) => new Set(text).size === text.length;
console.log(naive('Abba')); // false
console.log(naive('Aba')); // true, but 'a' repeats
console.log(naive('six-year-old')); // false, only the hyphen repeats
Without lowercasing, A and a look different, so Aba passes. Without stripping, the two hyphens in six-year-old count as a repeat, so a real isogram fails. Both bugs come from measuring the wrong thing.
Step 4: name the letter that repeated
A plain false is fine for a program. A person would rather know why. firstRepeat walks the letters and remembers each one it has seen:
const firstRepeat = (text) => {
const seen = new Set();
for (const c of text.toLowerCase().replace(/[^a-z]/g, '')) {
if (seen.has(c)) return c;
seen.add(c);
}
return null;
};
console.log(firstRepeat('lagos state')); // 's'
console.log(firstRepeat('lumberjack')); // null
seen.has(c) asks "have I met this letter before?". The first time the answer is yes, we return that letter. If the loop finishes, nothing repeated, so we return null.
In lagos state the letters are lagosstate. The second s comes straight after the first, so s is reported before the second a.
Step 5: edge cases and digits
const isIsogram = (text) => {
const letters = text.toLowerCase().replace(/[^a-z]/g, '');
return new Set(letters).size === letters.length;
};
console.log(isIsogram('')); // true
console.log(isIsogram('a')); // true
console.log(isIsogram('a11')); // true
An empty string has no letters, so none can repeat. A single letter is an isogram too. Digits are stripped by [^a-z], so a11 passes even though 1 appears twice. That is a choice, and the hint asks you to make it on purpose. If repeated digits should count, use [^a-z0-9] instead.
The full solution
The panel below has both functions and a loop that prints each test word with its repeated letter, if any. Press Run to see the table, and read the checks underneath.
const isIsogram = (text) => {
const letters = text.toLowerCase().replace(/[^a-z]/g, '');
return new Set(letters).size === letters.length;
};
// Which letter spoiled it, if any.
const firstRepeat = (text) => {
const seen = new Set();
for (const c of text.toLowerCase().replace(/[^a-z]/g, '')) {
if (seen.has(c)) return c;
seen.add(c);
}
return null;
};
for (const w of ['lumberjack', 'lagos state', 'six-year-old', 'Abba']) {
console.log(w.padEnd(14), isIsogram(w), firstRepeat(w) === null ? '' : '(repeat: ' + firstRepeat(w) + ')');
}
Output
11 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 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a word with no repeats', isIsogram('lumberjack'), true);
test('a repeat is caught', isIsogram('lagos state'), false);
test('and it can be named', firstRepeat('lagos state'), 's');
test('case does not hide a repeat', isIsogram('Abba'), false);
test('spaces and hyphens are stripped, not counted', isIsogram('six-year-old'), true);
test('the empty string is an isogram', isIsogram(''), true);
test('and so is a single letter', isIsogram('a'), true);
test('a Set drops duplicates, which is the whole trick', new Set('abba').size, 2);
test('while length keeps them', 'abba'.length, 4);
test('digits are stripped, so a repeated digit does not disqualify it', isIsogram('a11'), true);
test('the long standard example', isIsogram('dermatoglyphics'), true);
new Set(text).size === text.length is the whole idea, and it generalises: the same one-liner answers "are these values all distinct?" for any array.
Note that new Set('abba') works directly on the string, because a Set constructor takes any iterable and a string iterates its code points. That also means an emoji counts once here, unlike anything measured with length.
Returning which letter repeated costs three more lines and makes the function useful for an error message rather than only for a yes or no. Worth doing whenever the caller is a person.
Common mistakes
- Forgetting to lowercase.
Abathen looks like three different letters. Lowercase before you compare. - Counting spaces and hyphens.
six-year-oldfails because of its hyphens. Strip everything that isn't a letter first. - Stripping before lowercasing.
[^a-z]deletes capital letters. Lowercase first, then strip.
Try it yourself
- Change
isIsogramso a repeated digit also disqualifies the word, and test it with'a11'. - Write
allDistinct(array)that checks whether every value in an array is different, using the same Set trick. - Change
firstRepeatto return every repeated letter, so'lagos state'gives['s', 'a', 't'].