lonious
lonious

Reputation: 696

Javascript Palindrome Logic

I have checked this thread: Palindrome check in Javascript But I'm more so looking to fix my own algorithm. I am just programming online right now so I do not have access to a good debugger. So any hints/debugging problems found would be greatly appreciated. Here's the code:

function isPalindrome(str) {
if(str !== null && str !== undefined && str !== NaN) {
 var strStripped = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()@]/g,"");
 var strSqueezed = strStripped.replace(/ /g, "");
 var i, k;
 k = str.length-1;
 var numOfValidComparisons = 0;
  for(i=0; i<strSqueezed.length; i++) {
   if(strSqueezed.charAt(i) === strSqueezed.charAt(k)) {
     numOfValidComparisons++;
   }
   k--;
  }
 if(numOfValidComparisons === strSqueezed.length)
   return true;
 else
   return false;
   }
  return false;
}

I've written down the loop comparison logic on paper and have been baffled momentarily. If you're unfamiliar with what a palindrome is here: http://en.wikipedia.org/wiki/Palindrome

The test I'm working with right now is this string "race car" (and looks great on paper)

Upvotes: 2

Views: 476

Answers (1)

EyeOfTheHawks
EyeOfTheHawks

Reputation: 576

k = str.length-1;

should be

k = strSqueezed.length-1;

Thats it.

https://jsfiddle.net/aejmjsqk/

Upvotes: 1

Related Questions