DEV Community

Tadea Simunovic
Tadea Simunovic

Posted on

2

Anagrams in JavaScript(simple)

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
Enter fullscreen mode Exit fullscreen mode

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('')
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

πŸš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsβ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post β†’

Top comments (2)

Collapse
 
ceyhunkerti profile image
Ceyhun Kerti β€’

Nice and elegant, anagrams always remind me this scene

and here is the hard question: do anagrams have to be real words ?

Collapse
 
tadea profile image
Tadea Simunovic β€’

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.