Skip to content
Related Articles
Open in App
Not now

Related Articles

How to check a given string is an anagram of another string in JavaScript ?

Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 05 Jan, 2023
Improve Article
Save Article

Anagram: An anagram is a word or sentence, which usually contains all the original letters exactly once, in order to arrange the letters of a different term or phrase. Some of the examples are given below:

  • evil = vile
  • a gentleman = elegant man
  • eleven plus two = twelve plus one

Example 1: In this article, we will use in-built functions such as split(), sort(), and join() to check if a given string is an anagram of another string in JavaScript.

HTML




<script>
    function checkAnagram(a, b) {
     
        // Not of same length, can't be Anagram
        if (a.length !== b.length) {
            return false;
        }
     
        // Inbuilt functions to rearrange the string
        var str1 = a.split('').sort().join('');
        var str2 = b.split('').sort().join('');
     
        var result = (str1 === str2);
        return result;
    }
     
    // Checking the output
    console.log(checkAnagram('abc', 'cba'));
</script>


Output:

true

Example 2: In this article, we will the javascript for loop to check if a given string is an anagram of another string in JavaScript.

HTML




<script>
    function checkAnagram(a, b) {
        var array = {};
        if (a === b) {
            return true;
        }
        if (a.length !== b.length) {
            return false;
        }
        for (let i = 0; i < a.length; i++) {
            let res = a.charCodeAt(i) - 97;
            array[res] = (array[res] || 0) + 1;
        }
     
        for (let j = 0; j < b.length; j++) {
            let res = b.charCodeAt(j) - 97;
            if (!array[res]) {
                return false;
            }
            array[res]--;
        }
        return true;
    }
    console.log(checkAnagram('abc', 'cba'));
</script>


Output:

true

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!