Palindrome Algorithm
One of the more common exercises involving array methods is a palindrome algorithm. In case it's been awhile since you had an English class, a palindrome is a word, phrase, etc. that is spelled the same way forwards and backwards. A well-known example is the phrase A man, a plan, a canal, Panama!. The main character from the novel Holes, Stanley Yelnats, is also a palindrome.
Methods
You might remember from the last module that we'll need five string/array methods for our algorithm:
.replace()
.toLowerCase()
.split()
.reverse()
.join()
We'll start with a function block:
Lowercase and Non-AlphaNumeric Characters
The first thing we need to do is get rid of spaces and non-alphanumeric characters. Things like punctuation and spaces can mess up our algorithm. We also need to make all of our text lowercase, because the algorithm is case-sensitive.
To show you how these methods work, we'll use the string HoOps 1!
Our output is hoops1. Let's talk about what this code did:
.replace(/[^A-Z0-9]/gi,"")
takes out any character that is not a letter or number. Rememberg
is for global andi
means case-insensitive.The exclamation point and space are removed, our string is now HoOps1
.toLowerCase()
converts all text to lowercase.Our string is now hoops1
Reverse removeChar
We'll use the remaining three methods to reverse our string.
Our fist step is to split our string up into individual characters. We'll use the string sdrawkcab in this section, because irony.
Output
Next we'll reverse the order of our characters.
Output
Hilarious right? Finally, we'll join our reversed characters back into a single string.
And what do you know, our output is backwards!
Final check and output
Finally, we'll compare our initial string with our reversed string to see if it is in fact a palindrome. Check two strings, one palindrome and one non-palindrome.
Output
Our output is displayed as:
removeChar,
(initial string without non-alphanumeric characters all lowercase)checkPalindrome,
(removeChar reversed)boolean
(true or false based on whether or not our string is a palindrome)
Last updated