Like I said in the comment, your code doesn't work because it assumes both replace()
and toLowerCase()
augment their argument. But they don't, they return a new string instead of modifying the given one. So in your example _
symbol is still there in the comparing routine, messing up the expected result.
Another sidenote: when you base the result of a function on some comparison operation, there's no need to use if
. You can always replace this:
if (a === b) {
return true;
}
else {
return false;
}
... with simple:
return a === b;
Speaking about the task in general: while split-reverse-join-compare is the easiest approach (check @adeneo's comment for a nice one-liner), it's not optimal. Think about it: you only need to compare the halves of the string against each other. There's one way to do it:
function isDirectPalindrome(str) {
var i = 0, j = str.length - 1;
while (i < j) {
if (str.charAt(i++) !== str.charAt(j--)) {
return false;
}
}
return true;
}
function isPalindrome(str) {
return isDirectPalindrome(str.replace(/[\W_]+/g, '').toLowerCase());
}
There are two functions here: the first one always checks whether the string's a palindrome as is (no 'noise' symbols here), the second one normalizes a string beforehand. This makes it more simple to reuse the first one whenever you need it.
Of course, it's just a test. But I think it's convenient - and useful - to show both algorithms and modularity points here.