Check if two strings are anagrams in JavaScript
Beginner · 3 min read
Two words are anagrams when they use exactly the same letters, the same number of times, in a different order. "listen" and "silent" are anagrams. So are "Dormitory" and "Dirty Room", once you ignore capitals and spaces. Word games, puzzle apps and interview questions all ask for this check.
In this tutorial you will write isAnagram(a, b) by sorting letters, then a second version, isAnagramCounted, that counts letters instead. You need to know what a string, an array and a function are.
The idea: same letters, same counts
If two words are anagrams, sorting their letters into alphabetical order gives the same result:
listen -> e i l n s t
silent -> e i l n s t
Before sorting, both words need cleaning up so that capitals and spaces don't count. That step is called normalizing: making two inputs comparable by putting them in the same form.
Tools: replace and sort
toLowerCase() makes every letter small. replace with the pattern /[^a-z0-9]/g removes everything that isn't a small letter or a digit. Inside square brackets, ^ means "not", and the g flag means "every match, not just the first":
console.log('Dirty Room'.toLowerCase().replace(/[^a-z0-9]/g, '')); // dirtyroom
Strings can't be sorted directly, but arrays can. [...text] turns a string into an array of characters, sort() puts them in order, and join('') glues them back:
console.log([...'silent'].sort().join('')); // eilnst
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
47 Check whether two words are anagrams
easyDecide whether two words use exactly the same letters. Ignore case and spaces.
Stuck? Three hints, smallest first
- 1. Normalise both, then compare sorted letters.
- 2. Sorting is the clear answer; counting letters avoids the sort and is faster for long input.
- 3. Different lengths after normalising means no, so check that first and skip the work.
Step 1: normalize both words
Write the clean-up as its own small function, called normalise to match the answer, so both words get exactly the same treatment:
const normalise = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
console.log(normalise('Dormitory')); // dormitory
console.log(normalise('Dirty Room')); // dirtyroom
Step 2: compare the sorted letters
const normalise = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
function isAnagram(a, b) {
const x = normalise(a);
const y = normalise(b);
if (x.length !== y.length) return false;
return [...x].sort().join('') === [...y].sort().join('');
}
console.log(isAnagram('listen', 'silent')); // true
console.log(isAnagram('Dormitory', 'Dirty Room')); // true
console.log(isAnagram('hello', 'world')); // false
The length check is a shortcut. Two words of different lengths can't be anagrams, so there is no point sorting them.
Step 3: the wrong turn with a Set
A Set keeps one copy of each value, so it is tempting to compare the sets of letters. Try it on 'aab' and 'abb':
console.log([...new Set('aab')]); // [ 'a', 'b' ]
console.log([...new Set('abb')]); // [ 'a', 'b' ]
Both give a and b, so a Set comparison would say "anagram". It isn't: one word has two a's and the other has two b's. A Set forgets how many times each letter appears. Sorting keeps every letter, so the sorted version spots the difference:
console.log([...'aab'].sort().join('')); // aab
console.log([...'abb'].sort().join('')); // abb
Step 4: count instead of sort
Sorting is clear, but for very long text it does more work than needed. Counting is the other approach: count each letter in the first word, then subtract for each letter in the second word. If a letter runs out, or never appeared, the words aren't anagrams.
const normalise = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
function isAnagramCounted(a, b) {
const x = normalise(a);
const y = normalise(b);
if (x.length !== y.length) return false;
const counts = new Map();
for (const ch of x) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const ch of y) {
const left = counts.get(ch);
if (left === undefined || left === 0) return false;
counts.set(ch, left - 1);
}
return true;
}
console.log(isAnagramCounted('listen', 'silent')); // true
console.log(isAnagramCounted('aab', 'abb')); // false
A Map stores a count for each letter. ?? 0 means "use 0 if there is no count yet". Because the lengths already match, if no letter runs out, every count ends at zero, so you can return true.
The full solution
The answer panel has normalise, both versions and four sample pairs printed side by side. The checks include the 'aab' and 'abb' trap, a word against itself, empty strings, and both versions agreeing. Press Run to see the output.
const normalise = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
// The clear version.
function isAnagram(a, b) {
const x = normalise(a);
const y = normalise(b);
if (x.length !== y.length) return false;
return [...x].sort().join('') === [...y].sort().join('');
}
// The counting version: one pass each, no sort.
function isAnagramCounted(a, b) {
const x = normalise(a);
const y = normalise(b);
if (x.length !== y.length) return false;
const counts = new Map();
for (const ch of x) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const ch of y) {
const left = counts.get(ch);
if (left === undefined || left === 0) return false;
counts.set(ch, left - 1);
}
return true;
}
const pairs = [
['listen', 'silent'],
['Dormitory', 'Dirty Room'],
['hello', 'world'],
['aab', 'abb'],
];
for (const [a, b] of pairs) {
console.log(a.padEnd(11), b.padEnd(11), isAnagram(a, b));
}
Output
7 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 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a simple pair', isAnagram('listen', 'silent'), true);
test('case and spaces ignored', isAnagram('Dormitory', 'Dirty Room'), true);
test('different letters', isAnagram('hello', 'world'), false);
test('same letters, different counts', isAnagram('aab', 'abb'), false);
test('a word is an anagram of itself', isAnagram('lagos', 'lagos'), true);
test('empty strings match', isAnagram('', ''), true);
test('both methods agree', pairs.every(([a, b]) => isAnagram(a, b) === isAnagramCounted(a, b)), true);
'aab' against 'abb' is the case that catches a naive answer: same length, same set of letters, different counts. Comparing new Set contents would wrongly say yes. Sorting handles it because it compares multiplicities, and so does the counting version, which is the one to reach for when the strings are long.
Common mistakes
- Comparing Sets of letters. A Set ignores how many times a letter appears, so
'aab'and'abb'look the same. - Skipping the clean-up. Without lowercasing,
'D'and'd'are different letters, and the space in "Dirty Room" stops the lengths matching. - Normalizing only one word. Put the clean-up in one function and call it on both, so they can't drift apart.
Try it yourself
- Find every anagram of
'listen'in the list['enlist', 'google', 'inlets', 'banana']. - Group the words
['eat', 'tea', 'tan', 'ate', 'nat']by their sorted letters, so anagrams end up together. - Right now
normalisethrows away the é in "café", so "café" and "face" don't match. Change it so the é counts as an e. (Hint: look up the string methodnormalize('NFD').)