Check if two Strings are Anagrams?

JavaScript

Function to check if two strings are anagrams of each other:

Create a JavaScript function to check if two strings are anagrams of each other by comparing the sorted versions of the strings. Anagrams are words or phrases formed by rearranging the letters of another word or phrase. Here's a sample function to achieve this:

js Copy Code
function areAnagrams(str1, str2) {
    // Remove non-word characters and convert to lowercase
    const cleanStr1 = str1.replace(/[\W_]/g, "").toLowerCase();
    const cleanStr2 = str2.replace(/[\W_]/g, "").toLowerCase();

    // If lengths are different, they cannot be anagrams
    if (cleanStr1.length !== cleanStr2.length) {
        return false;
    }

    // Sort the characters in both strings and compare
    const sortedStr1 = cleanStr1.split("").sort().join("");
    const sortedStr2 = cleanStr2.split("").sort().join("");

    // If sorted strings are equal, they are anagrams
    return sortedStr1 === sortedStr2;
}

// Example usage:
const string1 = "listen";
const string2 = "silent";
console.log(areAnagrams(string1, string2)); // Output: true
Output:
true

This function first removes non-word characters and converts both input strings to lowercase. Then it sorts the characters in both strings and compares them. If the sorted strings are equal, then the original strings are anagrams of each other. Otherwise, they are not.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.