Introduction
Two strings are considered anagrams if they contain the same characters in the same frequency but in a different order. For example, "listen" and "silent" are anagrams because they have the same characters arranged differently. This guide will walk you through writing a JavaScript program to check if two strings are anagrams of each other.
Problem Statement
Create a JavaScript program that:
- Takes two strings as input.
- Checks if the two strings are anagrams.
- Displays whether the strings are anagrams or not.
Example:
Input:
"listen"
and"silent"
Output:
The strings are anagrams.
Input:
"hello"
and"world"
Output:
The strings are not anagrams.
Solution Steps
- Initialize the Strings: Accept or define two strings.
- Preprocess the Strings:
- Convert both strings to lowercase.
- Remove any non-alphabetic characters and white spaces.
- Sort and Compare:
- Sort the characters of both strings.
- Check if the sorted versions of the strings are the same.
- Display the Result: Output whether the two strings are anagrams.
JavaScript Program
// JavaScript Program to Check if Two Strings are Anagrams
// Author: https://www.rameshfadatare.com/
function areAnagrams(str1, str2) {
// Step 1: Remove non-alphabetic characters, convert to lowercase, and sort
const normalizeString = (str) => str.toLowerCase().replace(/[^a-z]/g, '').split('').sort().join('');
// Step 2: Compare the normalized versions of the strings
return normalizeString(str1) === normalizeString(str2);
}
// Example usage
const string1 = "listen";
const string2 = "silent";
if (areAnagrams(string1, string2)) {
console.log("The strings are anagrams.");
} else {
console.log("The strings are not anagrams.");
}
Explanation
Step 1: Remove Non-Alphabetic Characters and Sort
- The
normalizeString
function converts the input string to lowercase and removes any non-alphabetic characters usingreplace()
. - The
split('')
method splits the string into an array of characters, which is then sorted usingsort()
and joined back into a string usingjoin('')
.
Step 2: Compare the Normalized Strings
- If the sorted versions of both strings are identical, the strings are anagrams. Otherwise, they are not.
Output Example
The strings are anagrams.
Example with Different Input
const string1 = "hello";
const string2 = "world";
if (areAnagrams(string1, string2)) {
console.log("The strings are anagrams.");
} else {
console.log("The strings are not anagrams.");
}
Output:
The strings are not anagrams.
Handling Edge Cases
- Different Lengths: Strings with different lengths cannot be anagrams.
- You can add a condition to return
false
immediately if the lengths are different.
- You can add a condition to return
if (str1.length !== str2.length) {
return false;
}
- Empty Strings: If both strings are empty, they are considered anagrams.
Example with Edge Case Handling
function areAnagrams(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
const normalizeString = (str) => str.toLowerCase().replace(/[^a-z]/g, '').split('').sort().join('');
return normalizeString(str1) === normalizeString(str2);
}
const string1 = "apple";
const string2 = "pale";
if (areAnagrams(string1, string2)) {
console.log("The strings are anagrams.");
} else {
console.log("The strings are not anagrams.");
}
Output Example with Edge Case
The strings are not anagrams.
Conclusion
This JavaScript program checks if two strings are anagrams by normalizing, sorting, and comparing the characters. The solution efficiently handles edge cases such as strings with different lengths and non-alphabetic characters. This approach can be used for any scenario where detecting anagrams is required.
Comments
Post a Comment
Leave Comment