Check For Palindromes help please!

Check For Palindromes help please!
0

#1

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”);


#2

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


#3

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.


#4

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


#5

.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.


#6

It works here though :confused:


#7

Where? It did not work when I tried it.


#8

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


#10

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


#11

Thanks! That did it! :smiley: