Here is what I have so far:
function palindrome(str) {
const strArray = str
.toLowerCase()
.match(/[A-Za-z0-9]/g)
for (let i = 0; i < (strArray.length - 1) - i; i++) {
if (strArray[i + 0] !== strArray[(strArray.length - 1) - i]) {
return false
} else {
return true
}
}
}
My issue is with words like “barkab” or “almostomla” but I can’t see why the function doesn’t return false for these strings. Any palindrome I’ve tested has come back true.
So, when plugging “barkab” into the function, my thinking was:
-
break the string up into an array. this part seems to be working as expected and I don’t think there is an issue here.
-
then perform a for loop to iterate through each index and compare it with the end index minus the number of iterations; so for the first loop it would be comparing strArray[0 + 0] with strArray((strArray.length -1) - 0)
-
when i = 2; 2 < (6 - 1) - 2 //this is true so the loop will go on
if(strArray[0 +2] is not equal to strArray[(6 - 1) - 2] then return false;
if (r at index 2) is not equal to (k at index 3) then return false;
and yet the function returns true.
A nod in the right direction would be very helpful here. I feel like I’m glossing over something pretty simple. Or perhaps this isn’t the best way to perform the loop.