TypeScript: Check if Two Strings are Anagrams

1. Introduction

Anagrams are two words or phrases that rearrange the letters of one another to form the other. For instance, the word "listen" is an anagram of "silent". In this post, we'll detail the steps to determine whether two strings are anagrams using TypeScript.

2. Program Overview

Our TypeScript program will standardize the two strings by removing any non-alphanumeric characters and making them lowercase. After that, the program will compare the sorted characters of the two strings to determine if they are anagrams.

3. Code Program

// Function to determine if two strings are anagrams
function areAnagrams(str1: string, str2: string): boolean {
    // Standardize the strings
    const sanitizedStr1 = str1.replace(/\W/g, '').toLowerCase();
    const sanitizedStr2 = str2.replace(/\W/g, '').toLowerCase();

    // Sort and compare
    return sanitizedStr1.split('').sort().join('') === sanitizedStr2.split('').sort().join('');

// Test the areAnagrams function
const string1 = "Listen";
const string2 = "Silent";
console.log(`"${string1}" and "${string2}" are anagrams: ${areAnagrams(string1, string2)}`);


"Listen" and "Silent" are anagrams: true

4. Step By Step Explanation

1. We begin by defining the areAnagrams function, which takes two strings as parameters.

2. Inside the function, we first standardize both input strings. This involves:

- Removing any non-alphanumeric characters using the regular expression /\W/g.

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

3. Once the strings are standardized, we:

- Split each string into an array of characters with the split('') method.

- Sort the arrays with the sort() method.- Join the sorted arrays back into strings with the join('') method.

4. We then compare the sorted strings using the equality operator (===). If they match, the two original strings are anagrams.

5. Finally, we test our areAnagrams function with two example strings and display the results using console.log.

By following this approach, the TypeScript program can efficiently determine if two strings are anagrams.