How to make a Javascript Palindrome Checker
A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case and spacing.
2A33a2, 2A3 3a2, 2_A33#A2, racecar, RaceCar, and race CAR should all return true
.
We have a function named palindrome
which passes a str
parameter.
First, we replace all the non alphanumeric characters in the string
str = str.replace(/[^0-9a-z]/gi, '');
and turn all the characters in the string to lower case
str = str.toLowerCase();
Which can all be placed on a single line like so
str = str.replace(/[^0-9a-z]/gi, '').toLowerCase();
Next, we need to set a new variable with the string in reverse. First we split the string into an array of characters
let strRevArray = str.split('');
then we reverse the array
let strRevArrayReverse = strRevArray.reverse();
then we join the reversed array back into a string
let strRev = strRevArrayReverse.join('');
Again, all of this could be done in one line
let strRev = str.split('').reverse().join('');
Finally, we check to see if str is equal to strRev and return true if it is and false if it isn't. You could use an if
else
statement, but the easiest shorthand would be to use ternary
return(str == strRev);
the full code
function palindrome(str) {
str = str.replace(/[^0-9a-z]/gi, '').toLowerCase();
let strRev = str.split('').reverse().join('');
return (str == strRev);
}