How to Check for a Palindrome in JavaScript?

If you’re given a string, how do you check if it is a palindrome in JavaScript?

Note : A palindrome is a string that if spelled backwards or forwards will be the same. e.g. “level” spelled backwards or forwards is still “level”.

Below is the solution I came up with utilizing JavaScript built-in functions.

function palindromeChecker(str) {
    let cleaned = str.toLowerCase().replace(/\s/g, '');
    let reversed = cleaned.split("").reverse().join("");
    return cleaned === reversed ? true : false;
}

We are basically comparing the string with the reversed version of the string to check if they are still spelled the same way.

First, we have to “clean” the string, meaning we turn the string into lower case and remove white spaces from it with regex. We do it so we can have a more reliable result. Most likely, we wouldn’t want white spaces and capital letters to affect our palindrome check results, so we remove them.

(For more details on removing white spaces in JavaScript, refer to my other post! How to Remove Spaces from String in JavaScript?)

Next, we reverse the cleaned string and compare the cleaned string with the reversed cleaned string. If they match, then it is a palindrome.

(If you want further explanations on reversing a string, read here! How to Reverse a String in JavaScript?)

That’s an easier to read and more structured solution. If you want a one-liner solution, you can use the code below. It is the same code but without variables. It’s up to your preference which one you prefer more.

function palindromeChecker(str) {
    return str.toLowerCase().replace(/\s/g, '') === str.toLowerCase().replace(/\s/g, '').split("").reverse().join("") ? true : false;
}

Time complexity : O(n)

It’s quite tricky to determine the time complexity of built-in functions, but most likely the built-in functions used in the code iterates through each character from the string. So, it has O(n) time complexity.

Space Complexity : O(n)

Split function will result in a new array with elements equivalent to the length of the string. That means n space is used and O(n) space complexity for the algorithm.

Conclusion

That’s how you can check for a palindrome in JavaScript. You can utilize built-in functions and regex.

Let me know if you approach the problem in another way!

For you who want to brush up your JavaScript skills, whether to deepen or learn form zero, I recommend you try Codecademy. There are tons of JavaScript lessons that you can learn in a structured and interactive way. You can learn from the most basic materials to advanced stuffs and even preparing for technical interviews. Go try it now!

Check out the rest of my blog for more helpful contents on Data Structures and Algorithms in JavaScript!

See you next post!

Leave a Comment