JavaScript anagram comparison

前端 未结 16 2099
走了就别回头了
走了就别回头了 2020-12-17 02:30

I\'m trying to compare two strings to see if they are anagrams.

My problem is that I\'m only comparing the first letter in each string. For example, \"Mary\" and \"

16条回答
  •  [愿得一人]
    2020-12-17 03:06

    I think this is quite easy and simple.

    function checkAnagrams(str1, str2){
    
      var newstr1 = str1.toLowerCase().split('').sort().join();
      var newstr2 = str2.toLowerCase().split('').sort().join();
    
      if(newstr1 == newstr2){
        console.log("String is Anagrams");
      }
      else{
        console.log("String is Not Anagrams");
      }
    
    }
    
    checkAnagrams("Hello", "lolHe");
    checkAnagrams("Indian", "nIndisn");
    

提交回复
热议问题