Skip to main content

Bonfire: Check for Palindromes – Best Solution

By October 7, 2015Blog, Free Code Camp
Free Code Camp Bonfire: Palindromes

I decided to go back and post my solutions to some of the earlier challenges. I particularly like this one because it is an example of some interesting concepts to beginner coders.

Suggested methods include String.replace() and String.toLowerCase().

Best Solution

function palindrome(str) {
    // massage strings
    var strNormal = str.replace(/[^a-zA-Z0-9]/g,'').toLowerCase();
    var strReverse = strNormal.split("").reverse().join("");
    
    // compare strNormal vs strReverse
    return (strNormal === strReverse);
}

palindrome("not a palindrome");

And here’s a CodePen with my solution in action: http://codepen.io/allurewebsolutions/pen/gaWVBv

Code Breakdown

From Mozilla:

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

The toLowerCase() method returns the calling string value converted to lowercase.

We start the challenge by massaging the string str. We do this using the replace() method and replacing all characters in the string that are non-standard. In our regular expression /[^a-zA-Z0-9]/g, we are specifying to replace, with nothing (empty quotes) all characters that are not lower and uppercase A-Z as well as all numbers. The we convert the replaced string to lower case.

Next, we create the reverse of the strNormal. We use the methods Array.split(), Array.reverse(), and Array.join() all in one variable. First we split strNormal into an array. Then we reverse the order of the elements. Then we join each of the elements back into a string.

Finally, we compare whether strNormal equals strReverse. If it does, it is a palindrome and returns True. Otherwise, it returns False.

This solution to this challenge presents an interesting concept of using multiple methods at the same time. They work in left to right order and save the code of writing multiple variables. So in our case, split() is performed first followed by reverse() and lastly, join(). Each subsequent method is performed on the object modified by the previous method. I like to call this “method stringing.” I have no idea if an official name exists for this 🙂

Discussion

I would love to hear others’ solutions and discover better and cooler ways to solve these challenges. Please comment with your questions, suggestions, or anything you would like.

If you found my solution useful or learned something new from this blog post, please feel free add kudos inside the main chat of Free Code Camp: Thanks @allurewebsolutions

allure

Author allure

More posts by allure

Join the discussion 4 Comments

  • Aman Agarwal says:

    I’m not sure if you need to create a reverse string before checking for a palindrome. You can do it faster if you check for a palindrome right after you clean the string for non-alphanumeric chars. Check this one:

    function palindrome(str) {

    //First, converting string into a clean array with all lowercase, no spaces and no bullshit apart from alphabets.

    var newArr = (str.toLowerCase()).match(/[a-z]|[0-9]/g); //regular expressions to the rescue!

    //Now let’s test if the array is a palindrome, traversing the string only once
    for (i=0, len=newArr.length; i<len; i++) {
    if (newArr[i] != newArr[len – 1 – i]) {
    return false;
    }
    }
    return true;
    }

  • Aman Agarwal says:

    Yes, I agree it traverses the string multiple times, but I assumed that this would be the same way that the “str1 === str2” check works; is this faster than looping manually? If not, the main difference would be that it doesn’t require the creation of a temporary reversed string for comparison 🙂

    • I’m not sure how string comparisons work, whether they go through the string character by character, bit by bit. Or whether, they somehow look at it holistically. In my mind, avoid a for loop was a success for some reason 🙂

      Testing code tags:

      var code = "this is some code";

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017