JavaScript: Check if a given string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters)
JavaScript fundamental (ES6 Syntax): Exercise-206 with Solution
Write a JavaScript program to check if a given string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
- Use String.prototype.toLowerCase() and String.prototype.replace() with an appropriate regular expression to remove unnecessary characters.
- Use String.prototype.split(''), Array.prototype.sort() and Array.prototype.join('') on both strings to normalize them, then check if their normalized forms are equal.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const isAnagram = (str1, str2) => {
const normalize = str =>
str
.toLowerCase()
.replace(/[^a-z0-9]/gi, '')
.split('')
.sort()
.join('');
return normalize(str1) === normalize(str2);
};
console.log(isAnagram('iceman', 'cinema'));
console.log(isAnagram('madam', 'madam'));
Sample Output:
true true
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-206-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to check whether the provided argument is array-like (i.e. is iterable).
Next: Write a JavaScript program to that will return true if the given string is an absolute URL, false otherwise.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join