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

Let’s Compose Promises!

Progressive enhancement as a valuable philosophy in the age of JavaScript

Two JavaScript Coding Patterns that give you away as a Junior Developer

JS30 Challenge Day 04 — Array Cardio

List of buttons with text detailing the results of array methods for each dataset

Composition vs Inheritance and Thinking in React.js

React Currency Converter Application

Programming is art

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

Programming Language and Its Types

Why everyone should code

Errors are beautiful!

Why coding still matters