JavaScript Palindrome Checker: Simplifying String Reversal and Comparison

Learn how to verify if a string is a palindrome using javascript

When I first started participating in coding challenges to better my skills, one of the tasks was to "Write a function that accepts a string and returns true if the string is a palindrome or false if it is not."

While practicing javascript algorithm problems, I guarantee you must have come across a question similar to the one above. Even more confusing is the phrase "palindrome," if this is your first time hearing it.

In this article, I will explain what a palindrome is, and demonstrate how to use Javascript to determine whether a string is one or not.

To follow along with this article, you'll need the following:

  • Basic knowledge of javascript string and string methods

  • Basic understanding of functions and function expressions in javascript

  • Basic knowledge of javascript in general

Let's get started!

What is a Palindrome?

A palindrome is a word, number, phrase, or other sequence of symbols that reads the same backwards as forwards.

- Wikipedia

If a string reads in both directions when read forward and backward, it is referred to as a palindrome. Some examples include Dad, Madam, Race Car, Eye, Nurses Run, Civic, Level, Radar, Refer, etc.

Let's examine how to tell if a string is a palindrome now that we are aware of what one is.

But before we do so, let's look at a little function that will help us take out non-alphanumeric characters and convert our string to lowercase, leaving us with a clean collection of strings.

//function to convert our string to lower case and remove
//non-alphanumeric characters
const clearStr = (str) => str.toLowerCase().replace(/[\W_]/g, '')

//OR ES5

function clearStr(str){
   return str.toLowerCase().replace(/[\W_]/g, '')
   }

The function clearStr takes a string as input and returns a new string with all non-word(non-alphanumeric) characters removed.

The function first converts the string to lowercase using the toLowerCase() method. Then, it uses the replace() method to replace all non-word characters with empty strings. The empty string is represented by the literal ''.

Now that we've looked at how the function clearStr works, let's return to our main problem.

1.Using a For Loop

function isStringPalindrome(str){
     let neatStr = clearStr(str);
    //find the length of the string
     let strLength = neatStr.length;
     //iterate through half of the string length
    for(let i = 0; i < strLength / 2; i++){
       //check if the first and last string are same
       if(str[i] !== neatStr[strLength - 1 - i]{
            return false;
            }
            }
             return true;
        }

In the above program, the function isStringPalindrome takes a string, checks for the length then iterates through the characters using a for loop.

The if condition makes a comparison between the character at the position i from the beginning of the string and the character at the position i at the end of the string.

If any character throughout this iteration procedure does not equal its corresponding final string, the string is not considered a palindrome, and the function returns false.

In addition, since iterating over the entire string would require comparing each character twice, we just need to iterate through the first half of the string. Hence, we only do strLength / 2 total iterations.

2.Using built-in Functions

 function palindromeChecker(str){
   const neatStr = clearStr(str);

   //convert string to an array
   const arrayStr = neatStr.split('');

   // reverse the values of the new array
   const reverseStr = arrayStr.reverse()

   //convert the reversed array values back to a string
  const backToStr = reverseStr.join('')
    if(str === backToStr){
      console.log('It is a palindrome');
    }else{
      console.log('It is not a palindrome');
     }
     } 
        //you can also have this in a shorter form

  function palindromeChecker(str){
     const neatStr = clearStr(str);
     const reverseStr = neatStr.split('').reverse().join('')
     return  reverseStr === neatStr

    }

In the function palindromeChecker, the string is simply reversed, and then a comparison is made between the original string and the newly reversed string. It's a palindrome if they are equal.

We utilized javascript's inbuilt string methods to arrive at this solution

  • split() which breaks or converts the string into individual array characters.

  • reverse() reverses the position or order in an array.

  • join() which creates a string by concatenating the members of the array back together.

3.Using for..of

  function isPalindrome(str){
    const neatStr = clearStr(str);
    //convert string into an array
    const strArr = neatStr.split('');
    //use the for..of loop to iterate through each element of the
    // strArr array 
   for(let x of strArr){
    if(x !== strArr.pop()){
     return false
       }
       }
       return true
  }

Here, in the function isPalindrome we first convert the string to an array using the split() method, then iterate over each element of the new array. We then use the pop() method to remove the last entry from the array for each element, after which we compare the current element to that.

And as always, if any of these does not equal, we return false and the string does not pass off as a palindrome.

4.Using the map() method

function palindromeMap(str){
 const neatStr = clearStr(str);

//convert to an array and use the map() method on it
const strMap = neatStr.split('').map((x,i) => {
 return x !== neatStr[neatStr.length - 1 - i];
})
return strMap.some(n => !n);
}

Like the above functions, we first convert our string into an array, then use the map() method to return a new array, where each member is represented by a true or false value, indicating if it matches the character at the end.

Lastly, we use the some() method to check if our new array contains a false. If it does, then our string is not a palindrome.

So, which of these approaches performs better?

To help you choose which approach to employ, I've included the benefits and drawbacks of each method/technique in the table below, along with an estimate of how long each method will take to complete when a small or large string is handed to it, so you can choose the best approach.

MethodExecution Time(ms)ProsCons
For Loop0.0731 ms - 0.6272 msGreat performance even on large strings and we can go back as soon as we notice the first violation.This method appears a bit 'clumsy' as for-loops are not commonly used again thanks to ES6 and Babel.
Built-in Function0.1633 ms - 1.5192 msStraight to the point and easy to read.Not the best, particularly on little strings.
For...Of0.0415 ms - 0.9997 msperforms well and appears to be readable. Just like the for-loop , we can go back once we notice the first violation.The mutation(change) on the array using the pop() method cost us a bit of performance
Map0.0644 ms - 0.9630 msUtilizing ES6 techniques earns bonus points :).We are unable to break the iteration or guarantee that we would only do string.length / 2 iterations in total. Again, the map() method creates a new array or list which we have to iterate over for the second time after the first, costing us more memory space and performance as well.

Conclusion

Questions about Palindromes always show up in JavaScript coding challenges and job interviews. We have learned what makes a string a palindrome and ways to determine if a string qualifies to be one.

I hope you find this really helpful and I look forward to your thoughts in the comment section.

Thank you for reading!

References and Resources

Palindrome -Wikipedia

some() -MDN

for loop -MDN

string.length -MDN

reverse() method -MDN

split() -MDN

replace() -MDN

toLowerCase() -MDN

regular expressions -MDN

for...of -MDN

join() -MDN

pop() -MDN

map() -MDN