Search code examples
javascriptregexstringpalindrome

Determining if a string is a palindrome


I wanted to know where my logic is faulty. A string (str) is taken as an argument (the string could be lowercase, uppercase, with commas and periods) and set equal to var string. It is then reversed and if it equals the original string then the return value is true. If it is not equal a return value of false is displayed. Why does it evaluate everything as true?

 function palindrome(str) {
     var string =str.toLowerCase().replace(/\s/g, '').replace(/,/g , '').replace(/./g , '');

     if (string==string.split("").reverse().join("")) {
         return true;
     }
     else{
         return false;
     }      
}

palindrome("nope");

Solution

  • tl;dr replace the . in your last regex with a \. to strip out literal .s; right now, you're stripping out all characters.

    The Problem

    In regex, . matches any character (except new lines, \n, at least by default). So, this code replaces any character:

    replace(/./g , '')
    

    As a result, you're emptying the string. The reverse of an empty string is an empty string, so you always get a returned value of true.

    The Solution

    To match a literal period, you have to escape the . by writing \.. So, change that part to

    replace(/\./g , '')
    

    Some Refactoring to Make Your Code More Awesome

    You can also just return the result of your comparison; no need for the if/else block here. This would make your entire code (formatted for readability):

    function palindrome(str) {
        var string =str.toLowerCase()
                        .replace(/\s/g, '')
                        .replace(/,/g , '')
                        .replace(/\./g , '');
    
        return string==string.split("").reverse().join("");
    }
    
    palindrome("nope");
    

    You can go even further and just strip all non-alphabetical characters, so your code can be even simpler:

    function palindrome(str) {
        var string =str.toLowerCase().replace(/[^a-z]/g, '');
    
        return string==string.split("").reverse().join("");
    }
    
    palindrome("nope");