It works just fine with other palindromes (e.g "Able was I saw Elba.", "A man, a plan, a canal. Panama."), but fails with "almostoma".
function palindrome(str) {
str = str.toLowerCase();
str = str.split(" ").join("");
str = str.replace(",", "");
str = str.replace("_", "");
str = str.replace(".", "");
for (var i = 0; i < str.length; i++) {
if (str[i] == str[str.length - i - 1]) {
return true;
} else {
return false;
}
}
}
console.log(palindrome("almostoma"));
2
Answers
What your code does is that as soon as the
if (str[i] == str[str.length - i - 1])
is true, the program returns and it stops executing. Meaning only the last character is checked for equalityWhat I advise is to check for inequality only:
See the other answers and comment for the error you made
Here is a different approach