Introduction
In this lab, we will explore how to check if a given string is an anagram of another string. An anagram is a word or phrase formed by rearranging the letters of another, such as "iceman" and "cinema". We will use JavaScript to create a function that takes two strings as arguments and returns a boolean value indicating whether they are anagrams of each other or not.
JavaScript Function to Check if a String is Anagram
To check if a string is an anagram of another string, use the following JavaScript function. It's case-insensitive and ignores spaces, punctuation, and special characters.
const isAnagram = (str1, str2) => {
const normalize = (str) =>
str
.toLowerCase()
.replace(/[^a-z0-9]/gi, "")
.split("")
.sort()
.join("");
return normalize(str1) === normalize(str2);
};
To use the function, open the Terminal/SSH and type node. Then, call the function with two strings as arguments:
isAnagram("iceman", "cinema"); // true
The function uses String.prototype.toLowerCase() and String.prototype.replace() with an appropriate regular expression to remove unnecessary characters. It also uses String.prototype.split(), Array.prototype.sort(), and Array.prototype.join() on both strings to normalize them and check if their normalized forms are equal.
Summary
Congratulations! You have completed the String Is Anagram lab. You can practice more labs in LabEx to improve your skills.