2

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)

Community
  • 1
  • 1
lonious
  • 676
  • 9
  • 25
  • 2
    `str.replace(/\W/g,"")==str.split("").reverse().join("").replace(/\W/g,"")` – dandavis Mar 26 '15 at 20:45
  • Again, not looking for other answers I am looking to fix this one. – lonious Mar 26 '15 at 20:46
  • 3
    "I do not have access to a good debugger"... unless you're stuck in some ancient browser, what's wrong with the built-in console and associated tools? Chrome has an excellent debugger built in. – James Allardice Mar 26 '15 at 20:46
  • Also on a computer that doesn't allow saving to disk.. I'm not sure how to debug from code not saved on disk.. – lonious Mar 26 '15 at 21:16
  • Overall this code is garbage haha. At least I got to this point though. – lonious Mar 26 '15 at 21:47

1 Answers1

1
k = str.length-1;

should be

k = strSqueezed.length-1;

Thats it.

https://jsfiddle.net/aejmjsqk/

EyeOfTheHawks
  • 576
  • 1
  • 5
  • 16