Search code examples
javascriptpalindrome

I am having trouble with a palindrome function in javascript


This is my code: The function works well for inputs: "eye","race car","not a palindrome","A man, a plan, a canal. Panama","never odd or even"... However, it returns "true" when the input is "almostomla". Can someone please explain why?

function palindrome(str) {

  var newStr = str.replace(/[^0-9a-zA-Z]/g, '');
  newStr = newStr.replace(/\s+/g, '');
  newStr = newStr.toLowerCase();
  var arr = newStr.split('');
  var arr2 =[];

  for(x = 0; x < arr.length; x++){
    arr2.push(arr[arr.length-1-x]);
  }

  for(y = 0; y < arr.length; y++){
    if(arr[y] == arr2[y]){
      return true;
    }
    else{
      return false;
    }
  }

}

palindrome("almostomla");

Solution

  • I would really replace the palindrome checking function like below, after removing noise:

    function palindrome(str) {
      var newStr = str.replace(/[^0-9a-zA-Z]/g, '');
      newStr = newStr.replace(/\s+/g, '');
      newStr = newStr.toLowerCase();
      var arr = newStr.split('');
      return arr.join('') == arr.reverse().join('');
    }
    
    alert(palindrome("almostomla"));
    alert(palindrome("never odd or even"));

    Works as expected.

    Why doesn't your old code work?

    It checks only the first correct thing and returns true. You should remove the return true from there. Your code is as soon as first and last character are same, consider it as palindrome.

    So your code, corrected form will be:

    function palindrome(str) {
    
      var newStr = str.replace(/[^0-9a-zA-Z]/g, '');
      newStr = newStr.replace(/\s+/g, '');
      newStr = newStr.toLowerCase();
      var arr = newStr.split('');
      var arr2 = [];
    
      for (var x = 0; x < arr.length; x++) {
        arr2.push(arr[arr.length - 1 - x]);
      }
    
      for (var y = 0; y < arr.length; y++) {
        debugger;
        if (arr[y] != arr2[y]) {
          return false;
        }
      }
      return true; // Place it here to return after the whole loop.
    }
    
    alert(palindrome("almostomla"));
    alert(palindrome("never odd or even"));