JavaScript

Anagram in javascript

In this tutorial, we are going to see how to check if the two strings are anagrams or not in javascript. Two strings form an anagram, if and only if they contain the same number of characters, the order of the characters does not matter. If two strings are anagrams, one string can be rearranged to form the other string. For example:

  • abc and cba are anagrams.
  • listen and silent are also anagrams
 

Script to check if the two strings are anagrams
function isAnagram (str1, str2) {

    //Check if the two strings have different lengths
    if (str1.length !== str2.length) {
        return false;
    }
    
    //Sort the two strings
    var s1 = str1.split('').sort().join('');
    var s2 = str2.split('').sort().join('');

    //Compare the two sorted strings
    return (s1 === s2);
}

console.log(isAnagram('abc','cba'));
console.log(isAnagram('listen','silent')); 
console.log(isAnagram('dog','doog'));

Output:

true
true
false
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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