Check For Palindromes help please!

My code runs fine, the only problem is that it does not return false for palindromes that have underscores in them. Can someone please tell me why that is? Any help would be greatly appreciated! jHere is my code:

function palindrome(str) {
// Good luck!
var string = “”;
string = str.toLowerCase().replace(/\W/g, ‘’).split("").reverse().join("");
if (string === str.toLowerCase().replace(/\W+/g, “”)) {
return true;
}
else if (string != str) {
return false;
}

}

palindrome(“not a palindrome”);

The regex \w matches letters, numbers, and underscores. So \W will match anything that’s not any of those.

That’s what I thought. But it is not working to remove underscores for some reason. Do you know why? It works for all the cases except for the two cases with underscores in them.

I also tried making the regex (/[^A-Za-z0-9]/g, ‘’) and it still does not work. :confused:

.replace(/\W/g, '') will replace anything that’s not a letter, number, or underscore. With \W underscores will never be replaced. You have to change your regex so only letters and numbers are retained.

It works here though :confused:

Where? It did not work when I tried it.

Are you sure you replaced both regex in your code? (there are two of them)

I needed to replace my other regex…it works now! :smiley: Thanks!

Thanks! That did it! :smiley: