Sebastian Sebastian - 6 months ago 12
Javascript Question

Searching for palindromes with for loop

Simple code looking for palindromes. Wanted to do this without sequence (split -> reverse -> join -> compare). So i'm iterating. And i'm doing it wrong. Why?

function palindrome(str) {
str.toLowerCase().replace(/\[W_]/g, "").split('');
var j=str.length-1;
for (var i=0; i<str.length/2; i++)
{
if (str[i]!=str[j])
return false;
j--;

}
return true;
}


palindrome("race car");

Answer

You have a typo in your regex. It should be /[\W_]/g. Also, you forgot to assign the result to str. .replace() doesn't modify the original string, because strings in JavaScript are immutable.

Fixed code:

function palindrome(str) {
  str = str.toLowerCase().replace(/[\W_]/g, "").split('');
  var j=str.length-1;
  for (var i=0; i<str.length/2; i++) { 
    if (str[i]!=str[j])
      return false;
    j--;
  }
  return true;
}


palindrome("race car");