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.



JavaScript: Tips of the Day

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

const string = "foo";
const substring = "oo";

console.log(string.includes(substring));

includes doesn't have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1);

Ref: https://bit.ly/3fFFgZv