Hi Friends 👋,

Welcome To Infinitbility! ❤️

Today, I’m going to show How do I check if two strings are anagrams of each other in Javascript, here I will write a custom function to check if two strings are anagrams of each other or not.

What is an anagram?

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word anagram itself can be rearranged into nag a ram, also the word binary into brainy, and the word adobe into the abode.

Let’s start the today’s tutorial How do you check if two strings are anagrams of each other in Javascript?

Let’s understand how we can do

In the given strings ‘a’ and ‘b’, we will check if they are of the same length and then we will sort the strings. If both the strings are equal, then return “True”; if not, then print “False”.

  • Take Input two strings ‘a’ and ‘b’
  • A function checkAnagramStrings(string a, string b) which will return true if they are an anagram of each other otherwise false.
  • Find the length of both strings and check if they are the same.
  • Now sort both strings in lexicographical order and check if they are equal or not.
  • Return true or false accordingly.
// create checkAnagramStrings() which accept two parameter
function checkAnagramStrings(a, b) {
   // check length of both string  
   if(a.length !== b.length){
      return false;
   }
   
   // make array from string, sort the array, and make string
   let str1 = a.split('').sort().join('');
   let str2 = b.split('').sort().join('');
  
   // compare both string 
   if(str1 === str2){
      return true;
   } else { 
      return false;
   }
}

console.log(checkAnagramStrings("infinit", "tinifni")); // true
console.log(checkAnagramStrings("infinit", "bility")); // false

To validate the above program we have tried both valid cases and invalid cases, let’s check the output.

javascript, check if two strings are anagrams of each other example
javascript, check if two strings are anagrams of each other example

I hope it’s help you, All the best 👍.