0

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"));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Patrick
  • 19
  • 3
  • Your code is returning true directly if the first and the last characters match. You do not compare the other chars anymore. You should not return true if the characters match, but return false if they not match. When your loop is done you return true cause all characters match – Thallius Jul 07 '23 at 11:01
  • This function will return true for any string where the first and last characters are the same. Notice that you `return true` when `str[i] == str[str.length - i - 1]` -- this exits the function. What you should do is `continue` when that condition is true and only `return true` outside of your loop. – glhrmv Jul 07 '23 at 11:01
  • Related: [Does return stop a loop?](https://stackoverflow.com/a/11714515) – Nick Parsons Jul 07 '23 at 11:02
  • thank you @glhrmv for your help. I will try correcting my code. – Patrick Jul 07 '23 at 11:49

2 Answers2

2

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 equality

What I advise is to check for inequality only:

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 false;
    }
  }
  return true;
}
console.log(palindrome("almostoma"));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Thank you! I tried doing it your way and made some modifications to fit the requirements, and it worked! – Patrick Jul 07 '23 at 12:14
2

See the other answers and comment for the error you made

Here is a different approach

const palindrome = (str) => {
  str = String(str).toLowerCase(); // handle numbers too
  str = str.replace(/[^\p{L}\p{N}]/gu, ''); // remove all non characters unicode aware
  return str === [...str].reverse().join(''); // compare the reversed string
}

console.log(palindrome("almostoma"));
console.log(palindrome("Able was I saw Elba."))
console.log(palindrome("A man, a plan, a canal. Panama."))
console.log(palindrome(88000088))
mplungjan
  • 169,008
  • 28
  • 173
  • 236