Check for Anagram in 2 strings

前端 未结 4 1355
天命终不由人
天命终不由人 2021-01-26 19:16

I\'ve created a function that checks if 2 words are anagrams, but I want to make it better. I feel the declaration of the counter after in the if statement is not quite well, if

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-26 19:38

    Your code returns true for strings 'aabb' and 'abcc', which are not anagrams. You can just sort the strings and check if they're equal:

    function checkAnagram(string1, string2) {
       return string1.toLowerCase().split("").sort().join("") === string2.toLowerCase().split("").sort().join("")
    }
    

提交回复
热议问题