I'm writing a simple algorithm that checks if a string is a palindrome in javascript. This is what I have so far:
var isPalindrome = function(s) {
let i=0;
let j=s.length-1;
while (i < s.length && j >= 0) {
while (s[i].toLowerCase().match('[a-z0-9].') === false && i < s.length) {
i++;
}
while (s[j].toLowerCase().match('[a-z0-9].') === false && j >= 0) {
j--;
}
if ((s[i].toLowerCase()) !== (s[j].toLowerCase())) {
console.log(s[i].toLowerCase());
console.log(s[j].toLowerCase());
return false
} else {
i++;
j--;
}
}
return true;
};
The expected input can include non alphanumeric characters, e.g. .'";/, or whitespace, but they are to be ignored. For example,
"A man, a plan, a canal: Panama"
should return true, since once the string is stripped of any whitespace and punctuation, etc. it is a valid palindrome. My issue is that when I run this code on this example input, the console.log statements in the if loop above prints:
[whitepsace (a blank line)]
m
indicating in the first while loop, the statement s[i].toLowerCase().match('[a-z0-9].') is returning true when s[i] is a whitespace, causing the function to incorrectly return false, which doesn't make sense to me as my regex doesn't include whitespace in its character class. Why is this statement returning true for a whitespace character?
match('[a-z0-9].')matches for every character because of the unescaped..match('[a-z0-9]\.')is your way to go