Palindrome with a twist

Woodelin florveus
2 min readOct 8, 2021

The Problem

Many have stumbled upon the infamous palindrome algorithm question. The main goal of the palindrome question is to check whether or not the words are the same backward and if so return true. Seems simple however most of my test case in Leetcode did not pass. Some test cases had special characters and were still considered palindrome.

Steps to Finding the solution

With a bit of research, I was able to find a way to rid the string of special characters. I used the replace method and it came in clutch to achieve my algorithm. For example, given a word mixed with special characters. The replace method helps cut out the special characters you don’t need. Here is a better example below.

let string = "A man, a plan, a canal: Panama"let newStr =  string.replace(/[^a-zA-Z0-9]/g,"")

Getting the test case to pass

I proceeded to solve the problem starting by creating a variable that takes the string and gets rid of upper case letters and special characters. Here is a clear demonstration below.

let string = "A man, a plan, a canal: Panama"let newStr =  string.replace(/[^a-zA-Z0-9]/g,"").replace()

Solving the entire problem

I returned the variable and compared it to the original here’s a full demonstration below.

const palindrome = (string) => {let newStr = string.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()

return newStr.split('').reverse().join("") === newStr
}console.log(palindrome("A man, a plan, a canal: Panama"))

If you have any questions or comments I’ll be happy to answer. Till next time coders.

--

--