JavaScript: Check if Two Strings are Anagrams

1. Introduction

An anagram is a word or phrase that's formed by rearranging the letters of another word or phrase, using all the original letters exactly once. For instance, "listen" is an anagram of "silent". In JavaScript, we can develop a function to determine if two given strings are anagrams of each other.

2. Program Overview

For this guide, we will:

1. Create a function that checks if two strings are anagrams.

2. The function will clean up the strings, sort the characters, and then compare them.

3. We will test the function with some sample inputs.

3. Code Program

// Function to determine if two strings are anagrams
function areAnagrams(str1, str2) {
    // Remove any non-alphabet character and convert strings to lowercase
    let cleanedStr1 = str1.replace(/[^a-z]/gi, '').toLowerCase();
    let cleanedStr2 = str2.replace(/[^a-z]/gi, '').toLowerCase();

    // Sort the strings and compare them
    return cleanedStr1.split('').sort().join('') === cleanedStr2.split('').sort().join('');
}

let string1 = "listen";
let string2 = "silent";

if (areAnagrams(string1, string2)) {
    console.log(${string1} and ${string2} are anagrams.);
} else {
    console.log(${string1} and ${string2} are NOT anagrams.);
}

Output:

listen and silent are anagrams.

4. Step By Step Explanation

1. Cleaning the Strings: In the areAnagrams function, we first clean up the strings by:

- Removing any non-alphabet characters using the replace() method with a regular expression.

- Converting the strings to lowercase using the toLowerCase() method. This ensures our comparison is case-insensitive.

2. Sorting and Comparing the Strings:

- We then split each string into an array of characters with the split() method.

- We sort the array using the sort() method.

- We join the array back into a string with the join() method.

- Finally, we compare the two processed strings. If they are the same, then the original strings are anagrams.

3. Testing the Function: We define two strings, string1 and string2, and pass them to the areAnagrams function. We then display a message based on whether they are anagrams or not.

Comments