Anagram Check in JavaScript
Check if two strings are anagrams in JavaScript by sorting letters or counting them. "listen" and "silent" match. Full explanation, gotchas and output.
1// Anagram: Same characters, different order2// Examples: "listen" and "silent", "evil" and "vile"34// Method 1: Sort and compare5function isAnagram1(str1, str2) {6 // Normalize: lowercase, remove spaces7 str1 = str1.toLowerCase().replace(/\s/g, '');8 str2 = str2.toLowerCase().replace(/\s/g, '');910 // Sort and compare11 return str1.split('').sort().join('') ===12 str2.split('').sort().join('');13}1415console.log("listen & silent:", isAnagram1("listen", "silent"));16console.log("hello & world:", isAnagram1("hello", "world"));17console.log("The Morse Code & Here come dots:",18 isAnagram1("The Morse Code", "Here come dots"));1920// Method 2: Character frequency count21function isAnagram2(str1, str2) {22 str1 = str1.toLowerCase().replace(/\s/g, '');23 str2 = str2.toLowerCase().replace(/\s/g, '');2425 if (str1.length !== str2.length) return false;2627 let count1 = {};28 let count2 = {};2930 // Count characters in str131 for (let char of str1) {32 count1[char] = (count1[char] || 0) + 1;33 }3435 // Count characters in str236 for (let char of str2) {37 count2[char] = (count2[char] || 0) + 1;38 }3940 // Compare counts41 for (let char in count1) {42 if (count1[char] !== count2[char]) {43 return false;44 }45 }4647 return true;48}4950console.log("\nUsing frequency:");51console.log("listen & silent:", isAnagram2("listen", "silent"));52console.log("aabb & abab:", isAnagram2("aabb", "abab"));5354// Method 3: Single object count55function isAnagram3(str1, str2) {56 str1 = str1.toLowerCase().replace(/\s/g, '');57 str2 = str2.toLowerCase().replace(/\s/g, '');5859 if (str1.length !== str2.length) return false;6061 let count = {};6263 // Increment for str164 for (let char of str1) {65 count[char] = (count[char] || 0) + 1;66 }6768 // Decrement for str269 for (let char of str2) {70 if (!count[char]) return false;71 count[char]--;72 }7374 return true;75}7677console.log("\nSingle object:");78console.log("evil & vile:", isAnagram3("evil", "vile"));
Sample Output
listen & silent: true hello & world: false The Morse Code & Here come dots: true Using frequency: listen & silent: true aabb & abab: true Single object: evil & vile: true
In this one
- What makes two words anagrams
- How sorting letters gives a fingerprint
- How to count letters with an object
- Why you normalise case and spaces first
How it works
- 1
Both words are lowercased and spaces removed.
- 2
Sorting gives "eilnst" for listen and silent.
- 3
hello and world sort differently, so false.
- 4
Frequency counts match for aabb and abab.
- 5
The single-object method confirms evil and vile.
Edge cases
Different lengths
"abc" and "abcc" are not anagrams.
Methods 2 and 3 check length first and return false early.
Punctuation
"dormitory!" vs "dirty room" fails.
Only spaces are removed here. Strip punctuation with a wider regex if needed.
Same word twice
isAnagram1("cat", "cat") is true.
By this rule a word is its own anagram. Add a check if you want different words.
What's going on
Two words are anagrams if they use the same letters the same number of times, in any order. "listen" and "silent" are anagrams. So are "evil" and "vile".
All methods first normalise the text. toLowerCase() stops "Listen" and "silent" from failing over one capital letter. replace(/\s/g, '') removes spaces, so phrases like "The Morse Code" and "Here come dots" can match. Whether spaces should count is your choice. This page strips them.
Method 1 sorts. It splits each string into letters, sorts them, and joins them back. "listen" and "silent" both become "eilnst". If the two sorted strings are equal, they are anagrams. It is short and easy to trust.
Method 2 counts letters. It builds an object for each word, where each key is a letter and each value is how many times it appears. (count1[char] || 0) + 1 starts a new letter at 0 and adds 1. Then it compares the two counts. It checks lengths first, so a word with extra letters fails fast.
Method 3 uses one object. It adds 1 for each letter of the first word and subtracts 1 for each letter of the second. If a letter is missing or runs out, !count[char] is true and the answer is false.
Counting is faster than sorting for long strings. Sorting is simpler to read.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Are "night" and "thing" anagrams?
Pick an answer to check it.
Question 2
What does "cab".split("").sort().join("") return?
Pick an answer to check it.
Questions people ask
Why sort the letters?
Sorting puts letters in a fixed order. Anagrams end up as the same string.
What does (count[char] || 0) mean?
If the letter has no count yet, use 0. Then add 1.
Which method should I use?
Sorting for clarity. Counting for long text.