I'm currently learning JavaScript on FreeCodeCamp, and I have to do a palindrome checker. I tried to write my own code to do it, most of the check tests needed for the validation return the correct and expected answer. But three of the check tests are not good. I've been searching why but I can't figure it out.
In this exercise, I have to isolate non alphanumerics characters from the string, and check if the string is a palindrome without those.
Values incorrect :
str = "_eye" (should return true)
str = "almostomla" (should return false)
str = "My age is 0, 0 si ega ym." (should return true)
My code at the moment :
function palindrome(str) {
const nonAlpha = /^[^a-zA-Z0-9]+$/gi;
str.replace(nonAlpha, ""); // replacing non alphanumerics characters with a regex
const lowerCaseString = str.toLowerCase(); // converting string to lower case
let strMaxIndex = str.length - 1; // checking what is the max index of str
let startIndex = 0;
while (startIndex !== strMaxIndex) {
if (lowerCaseString[startIndex] === lowerCaseString[strMaxIndex]) { // checking if characters from the left are the same from the right
startIndex += 1; // going from left to center of str
strMaxIndex -= 1; // going from right to center of str
return true;
} else if (lowerCaseString.length <= 2) { // can't be a palindrome if it has only 2 characters
return false;
} else {
return false;
}
}
}
palindrome("eye");