skip to Main Content

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


  1. 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"));
    Login or Signup to reply.
  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))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search