Emmanuel Akinfulubi

JavaScriptString

Check if two phrases are anagrams in JavaScript

Intermediate · 3 min read

Two words are anagrams when one is made from exactly the same letters as the other, rearranged: listen and silent, or dormitory and dirty room. Word games, puzzle apps and coding interviews all ask you to check for them.

In this tutorial you will write isAnagram by putting both phrases into the same tidy form and comparing. Then you will write a second version that counts letters instead of sorting. You should know how toLowerCase, replace with a regex and sort work. Each is used in a simple way here.

The idea: a normal form

If two phrases use the same letters, then sorting their letters gives the same result. listen sorted is eilnst, and so is silent. So we turn each phrase into a normal form, a standard version that ignores everything we don't care about, and compare the two.

For this exercise "everything we don't care about" is case, spaces and punctuation. So the normal form is: lowercase, remove every character that isn't a letter or digit, then sort.

Sorting characters

Arrays can be sorted, strings can't. So we spread the string into an array of characters, sort it, and join it back: [...text].sort().join(''). With no compare function, sort puts characters in the order of their character codes, which for lowercase letters is alphabetical.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

41 Are two strings anagrams?

fair

Decide whether 'Dormitory' and 'dirty room' are anagrams. Ignore case, spaces and punctuation.

Stuck? Three hints, smallest first
  1. 1. Normalise both strings the same way, then compare.
  2. 2. Sorting the characters is the shortest normal form.
  3. 3. Equal length is necessary but not sufficient, so do not stop there.

Step 1: clean the text

Step 1

console.log('Dirty room'.toLowerCase().replace(/[^a-z0-9]/g, '')); // 'dirtyroom'

[^a-z0-9] matches any character that is not a lowercase letter or digit, and the g flag removes all of them. Lowercasing first means capitals are kept as small letters instead of being deleted.

Step 2: sort the letters

Step 2

const normalise = (text) =>
  [...text.toLowerCase().replace(/[^a-z0-9]/g, '')].sort().join('');
console.log(normalise('silent'));     // 'eilnst'
console.log(normalise('Dormitory'));  // 'dimoorrty'
console.log(normalise('dirty room')); // 'dimoorrty'

The function keeps the name normalise used in the answer. Both phrases come out as dimoorrty, so they are anagrams.

Step 3: compare the normal forms

Step 3

const normalise = (text) =>
  [...text.toLowerCase().replace(/[^a-z0-9]/g, '')].sort().join('');
const isAnagram = (a, b) => normalise(a) === normalise(b);
console.log(isAnagram('listen', 'silent'));     // true
console.log(isAnagram('Listen', 'SILENT'));     // true
console.log(isAnagram('Dormitory', 'dirty room')); // true
console.log(isAnagram('lagos', 'kano'));        // false

That is the whole check. Case, spaces and punctuation don't matter, because the normal form removed them.

Step 4: same length is not enough

A tempting shortcut is to compare lengths, or check that every letter of one word appears in the other. Both let wrong answers through:

Step 4

const normalise = (text) =>
  [...text.toLowerCase().replace(/[^a-z0-9]/g, '')].sort().join('');
const isAnagram = (a, b) => normalise(a) === normalise(b);
console.log(isAnagram('abc', 'abd')); // false
console.log(isAnagram('aab', 'abb')); // false

abc and abd have the same length but different letters. aab and abb use the same letters in different amounts. Sorting catches both, because the sorted forms differ.

Step 5: edge cases

Step 5

const normalise = (text) =>
  [...text.toLowerCase().replace(/[^a-z0-9]/g, '')].sort().join('');
const isAnagram = (a, b) => normalise(a) === normalise(b);
console.log(isAnagram('lagos', 'lagos')); // true
console.log(isAnagram('', ''));           // true
console.log(normalise('a1'));             // '1a'

A word is an anagram of itself, and two empty strings are too. Digits sort before letters, because their character codes are smaller. That doesn't matter here: the sorted form is only ever compared with another sorted form, so any consistent order works.

Step 6: count instead of sorting

Sorting is short and clear. For very long texts there is a faster way: count each letter in the first phrase, then count down for the second. If every count ends at zero, the letters match.

Step 6

const normalise = (text) =>
  [...text.toLowerCase().replace(/[^a-z0-9]/g, '')].sort().join('');
function isAnagramByCount(a, b) {
  const x = normalise(a);
  const y = normalise(b);
  if (x.length !== y.length) return false;
  const counts = new Map();
  for (const c of x) counts.set(c, (counts.get(c) ?? 0) + 1);
  for (const c of y) {
    if (!counts.has(c)) return false;
    counts.set(c, counts.get(c) - 1);
    if (counts.get(c) === 0) counts.delete(c);
  }
  return counts.size === 0;
}
console.log(isAnagramByCount('listen', 'silent')); // true
console.log(isAnagramByCount('aab', 'abb'));       // false

A Map stores a count for each letter. The first loop counts up. The second loop counts down, stops early if it meets a letter the first phrase didn't have, and deletes a letter once its count reaches zero. An empty map at the end means every letter matched. Here the length check is a useful early exit, because different lengths can never be anagrams.

The full solution

Here is the complete answer: normalise, isAnagram, the counting version and checks that the two versions agree. Press Run to see both normal forms for 'Dormitory' and 'dirty room'.

The answer

const normalise = (text) =>
  [...text.toLowerCase().replace(/[^a-z0-9]/g, '')].sort().join('');

const isAnagram = (a, b) => normalise(a) === normalise(b);

// Counting is the other standard answer, and it is linear rather than n log n.
function isAnagramByCount(a, b) {
  const x = normalise(a);
  const y = normalise(b);
  if (x.length !== y.length) return false;
  const counts = new Map();
  for (const c of x) counts.set(c, (counts.get(c) ?? 0) + 1);
  for (const c of y) {
    if (!counts.has(c)) return false;
    counts.set(c, counts.get(c) - 1);
    if (counts.get(c) === 0) counts.delete(c);
  }
  return counts.size === 0;
}

console.log("normalise('Dormitory') :", normalise('Dormitory'));
console.log("normalise('dirty room'):", normalise('dirty room'));
console.log('anagrams?', isAnagram('Dormitory', 'dirty room'));

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.

11 checks

test('listen and silent', isAnagram('listen', 'silent'), true);
test('case is folded', isAnagram('Listen', 'SILENT'), true);
test('spaces and punctuation are ignored', isAnagram('Dormitory', 'dirty room'), true);
test('different letters are not anagrams', isAnagram('lagos', 'kano'), false);
test('the same letters in different amounts are not either', isAnagram('aab', 'abb'), false);
test('a word is an anagram of itself', isAnagram('lagos', 'lagos'), true);
test('two empty strings are anagrams', isAnagram('', ''), true);
test('sorting is what makes the comparison work', normalise('silent'), 'eilnst');
test('sort compares code units, so digits come before letters', normalise('a1'), '1a');
test('equal length is not enough on its own', isAnagram('abc', 'abd'), false);
test('the counting version agrees everywhere', [['listen', 'silent'], ['aab', 'abb'], ['abc', 'abd'], ['', '']].every(([a, b]) => isAnagramByCount(a, b) === isAnagram(a, b)), true);

Sort-and-compare is the answer to give: it is one line, obviously correct, and n log n on string lengths that are almost always tiny. The counting version is linear and worth knowing for when the strings are not tiny.

sort() with no comparator compares UTF-16 code units, which is exactly what is wanted here — any consistent total order works, because the sorted form is only ever compared against another sorted form. That is also why normalise('a1') being '1a' is harmless rather than a bug.

Common mistakes

  • Removing characters before lowercasing. [^a-z0-9] would delete the capital letters. Lowercase first.
  • Only comparing lengths. abc and abd have the same length. Compare the sorted letters.
  • Sorting a string directly. Strings have no sort. Spread into an array first.

Try it yourself

  1. Group ['listen', 'silent', 'enlist', 'lagos', 'goals'] into lists of anagrams.
  2. Change the cleaning step so accented letters are kept and compared too.
  3. Write isAnagramOfPalindrome(text): can the letters be rearranged into a palindrome?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.