String Is Anagram

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28409{{"`String Is Anagram`"}} javascript/data_types -.-> lab-28409{{"`String Is Anagram`"}} javascript/arith_ops -.-> lab-28409{{"`String Is Anagram`"}} javascript/comp_ops -.-> lab-28409{{"`String Is Anagram`"}} end

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.

Other JavaScript Tutorials you may like