Check for Palindromes exercise

Check for Palindromes exercise
0.0 0

#1

Hello forum users,

could you please assist me why my code is failing the tests to check for palindromes

function palindrome(str) {
var newStr=str.replace(/[^a-zA-Z0-9]/g, ‘’).toLowerCase();
newStr=newStr.split(’’);
var newStrRev=newStr.reverse();

for(var i=0;i<newStrRev.length;i++)
{
if(newStr[i]!=newStrRev[i])
{
return false;
}

}

return true;
}

palindrome(“eye”);


#2

Try to console.log() your vars !


#3

OK, this one took me a second.

Just as basic error checking, you should learn how to use console.log to check to make sure what you think is happening is really happening. It will save you a lot of headaches.

The problem is in your line var newStrRev=newStr.reverse();

Array.reverse() not only returns the changed array, it also reverses the original,. So your function is comparing two reversed arrays, the same reversed arrays, so it will always return true.

Yes, it’s a little confusing - some functions return the changed data without affecting the original, some change the original.

So you have to copy the first array to the second, and then reverse that. But be careful, copying arrays isn’t as simple as arr2 = arr1; - because they are objects, they are referenced by address and that is basically saying that arr2 wants to point to the same data structure that arr1 does. So to copy arrays, you need something like *arr1 = arr2.split();

And to make your code a little faster, you don’t need to check the whole array. Once you’ve confirmed that the front half of one is equal to the front half of the other, then you don’t need to check the back halves since they are just reversed copies of the front halves of the other.


#5

First there’s a little mistake in your .replace(regex) function.
Second you don’t have to use arrays once the str is reversed. For example ‘race car’ after .replace() is ‘racecar’.


#6

@ksjazzguitar @djebar-fermas thanks alot mates your answers were very helpful. I was able to sort it out.


#7

I didn’t want to give you the solution, but help you to understand how you can debug your code. I think that you can’t learn programming just by copy and paste code !
So, if you understood your mistakes, here’s my solution:

function palindrome(str){
    str=str.toLowerCase().replace(/[^a-z]/g,'');
    return (str  === str.split('').reverse().join(''));
}
palindrome('A_(\\_|)b*a\\2'); //return true; "aba"==="aba"