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.
Challenge
Given two strings, write an algorithm to check if they are anagrams of each other. Return true if they pass the test and false if they don't. E.g
anagrams('rail safety', 'fairy tales') --> True
anagrams('Cat', 'Act') --> True
anagrams('Save!', 'vase') --> True
anagrams('Hi there', 'Bye there') --> False
We need to create a function that will take two strings as an argument and compare them to see if they contain the same characters that are used the same number of times.
I will create a helper function to avoid errors, removing extra spaces, punctuation marks if any, and lower case both strings.
function cleanString(str) {
return str.replace(/[^\w]/g,'').toLowerCase().split('').sort().join('')
}
In this function I'm using RegExp.
Since we use sort() method that belongs to arrays we will need to temporarily turn a string to an array with split() method, sort() it and turn back to a string with join()
Let's call this helper method to compare two strings, like so:
function anagrams(stringA, stringB) {
return cleanString(stringA) === cleanString(stringB)
}
function cleanString(str) {
return str.replace(/[^\w]/g,'').toLowerCase().split('').sort().join('')
}
console.log(anagrams("Hello","!@#ElLoH")) // true
console.log(anagrams("Helo","!@#ElLoH")) // false
Top comments (2)
Nice and elegant, anagrams always remind me this scene
and here is the hard question: do anagrams have to be real words ?
I love that movie!
No, they don't have to be real words, the point is to contain the same characters that repeat the same number of times.