Palindrome Checker
JavaScript Algorithms and Data Structures Projects — freeCodeCamp
Problem Description : Return true
if the given string is a palindrome. Otherwise, return false
.
A palindrome is a word or sentence that’s spelled the same way both forward and backward, ignoring punctuation, case, and spacing.
Note: You’ll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything into the same case (lower or upper case) in order to check for palindromes.
We’ll pass strings with varying formats, such as racecar
, RaceCar
, and race CAR
among others.
We’ll also pass strings with special symbols, such as 2A3*3a2
, 2A3 3a2
, and 2_A3*3#A2
.
Solution Steps:
- We will be given a string. Problem description itself gives us many clues -how to approach the solution. First of all, making the given string plain without any other symbols or any special characters other than alphanumeric characters, will make our life easier.
(Alphanumeric characters are : English letters and digits) - To do that, we can use Regular Expressions to replace all non-alphanumeric characters with no-character i.e. “” in the given string then convert it to an array of characters using
split()
method of a string.
/[^a-z0-9]/gi
this selects every character except letters and digits.
- plainStrArr is an array of each character (changed to lowerCase, using
toLowerCase()
method)of plain string as it’s elements. - plainStr is string form of plainStrArr to compare at the end.
- plainRevStr is string form of reversed array of plainStrArr.
- Now compare both the strings and write true if they are same and false if they are not.
Oh, Yeah ! That’s it. Here’s the code :
function palindrome(str) {
let regEx = /[^a-z0-9]/gi;
let plainStrArr = str.replace(regEx,'').toLowerCase().split('');
let plainStr = plainStrArr.join('');
let plainRevStr = plainStrArr.reverse().join('');return plainStr === plainRevStr ? true : false;
}palindrome("1 eye for of 1 eye."); //false
palindrome("My age is 0, 0 si ega ym."); //true
palindrome("0_0 (: /-\ :) 0-0"); //true
Thank You !
I would be happy to hear your suggestions/improvements.