The \ W meta-detector is used to search for a character without a word. The word character is the character from az, AZ, 0-9,, including the underscore . This means that if you use [\ W] and not [\ W _]
var normalizedStr = str.replace(/[\W]/g, '').toLowerCase();
your normalizedStr will contain an underscore after replacement.
Since this call requires the removal of all non-alphanumeric characters (punctuation, spaces and characters), it will return unwanted results for any processed strings that include "_":
palindrome ("_ eye") - should return true, but instead it will be false;
palindrome ("0_0 (: / - \ :) 0-0") - should return true, but instead will be false;
In addition, instead of converting a string to an array, cancel it and convert it back to a string before comparison, it is better to use a loop to compare arrays for better performance (especially if the string is larger):
function palindrome(str) { var clearString = str.toLowerCase().replace(/[^0-9a-z]/gi, '').split(''); for (var i = 0; i < clearString.length/2; i++) { if (clearString[i] !== clearString[clearString.length -1 -i]) { return false; } } return true; }
Keep in mind that the false statement must be the first and the true statement must be outside the for loop , otherwise it will break the function after the first match and return an inaccurate result.
source share