Palindrome with a twist

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.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Getting Started with the MediaStream API

image showing that a track gets added to the MediaStream object when addTrack is called

Screen intro/splash/preloader using document resources downloading percentage

JavaScript Libraries You Should Know

RxJs, Streams & the Ford Assembly Line

Why you HAVE to unsubscribe from Observable

I built an app that searches an API with React

Creating an offline-first React Native app

Unreal Engine. Change Third-Person Character to a First-Person

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Woodelin florveus

Woodelin florveus

More from Medium

Pros and Cons of Chrome Extension for indie developer

Advantages of Pair Programming

Jean Bartik and Betty Snyder

General Interview Questions for Web Development Entry Roles

cs371p Spring 2022 Week 3: Badr Belhiti