Anagram Check in JavaScript
Sort both strings. If they match, anagram. Listen and silent.
IntermediateString ProgramsExample 4 of 5
anagram-check.js
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"));
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
What's going on
split('').sort().join('') on both. Skip lowercasing and Listen vs silent fails.
Spaces: decide whether they count. This page usually strips them.