JavaScript anagram comparison

前端 未结 16 2162
走了就别回头了
走了就别回头了 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 02:58

    This considers case sensitivity and removes white spaces AND ignore all non-alphanumeric characters

    function compare(a,b) {
        var c = a.replace(/\W+/g, '').toLowerCase().split("").sort().join("");
        var d = b.replace(/\W+/g, '').toLowerCase().split("").sort().join("");
            return (c ===d) ? "Anagram":"Not anagram";
    }

提交回复
热议问题