Check Two Strings Are Anagrams Of Each Other Or Not In JavaScript

In this article, we learn to check whether two strings are anagrams of each other or not in JavaScript.

For that follow the below steps:-

Step 1: Take two strings string 1 and string 2.

Step 2: To check whether string 2 is an anagram of string 1 then, first check the length of both the strings. If they are not equal, then string 2 cannot be anagrams of string 1.

Step 3: Now check letters on both strings, if letters exist in both strings then they are anagrams of each other.

Now create one Html file and add the following it.

<!DOCTYPE html>
<html>
  <body>
    <div>a = <span id="a"></span> </div>
    <div>b = <span id="b"></span></div>
    <div>str1 = <span id="str1"></span> </div>
    <div>str2 = <span id="str2"></span></div>
    <div id="output"></div>

    <script>
      let a = "india";  
      let b = "nidia";  

      document.getElementById("a").innerHTML = a;
      document.getElementById("b").innerHTML = b;

      if(a.length==b.length){
     
        let str1 = a.split('').sort().join('');
        let str2 = b.split('').sort().join('');
   
        document.getElementById("str1").innerHTML = str1;
        document.getElementById("str2").innerHTML = str2;

        if(str1 === str2){
          document.getElementById("output").innerHTML = "Both the strings are anagrams of each other";
        }
        else{
          document.getElementById("output").innerHTML = "Both the strings are not anagrams of each other";
        }
      }
      else{
        document.getElementById("output").innerHTML = "Both the strings are not anagrams of each other"
      }
    </script>

  </body>
</html>

Output:-

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories