Anagram
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Consider capital letters to be the same as lower case
Examples
anagram(‘Dormitory’ , ‘Dirty room’) = true
anagram(‘The earthquakes’ , ‘The queer shakes’) = true
anagram(‘Astronomer’ ,’Moon starrer’) = true
anagram(‘Hello World’ , ‘Bye There’) = false
function anagrams(stringA, stringB) {
return cleanString(stringA) === cleanString(stringB);
}
function cleanString(str) {
return str.replace(/[^\w]/g, '').toLowerCase().split('').sort().join('');
}
First we create function anagrams with parameters stringA and stringB.
Then we create helper function cleanString with parameter str and we return str.replace which is build in JavaScript method. replace will strip out any spaces or any punctuation and turn into lowercase with chaining the toLowerCase();
Than we chain .split(‘’) method to turn the string str into array
Then we chain .sort() method to sort alphabetically the characters from the array done with split method
In the end we join the characters from the array, sorted with sort method and now joined with .join(‘’) method. All these functions are build in JavaScript helpers
From the cleanString function all these tasks done above are returned
In the main function anagrams we return cleanString(stringA) === cleanString(stringB) and if it is true it is anagram.