w3resource

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:

JavaScript Fundamental: Check whether a given string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
JavaScript Fundamental: Check whether a given string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).

Flowchart:

flowchart: Check whether a given string is an anagram of another string

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.



Follow us on Facebook and Twitter for latest update.