Subscribe

Vanilla JavaScript palindrome checker in 3 lines

✍️

Lets see how we can make a super easy palindrome checker in JavaScript

10 Oct, 2020 · 2 min read

There comes a time in your life when you need a palindrome checker!

You might now think, what is a palindrome?

It’s a word or sentence like mom that you can reverse, and it’s still mom!

If that time comes, think about this article and how to check for palindromes in JavaScript.

We will be building this fantastic palindrome function. Try it out on my Codepen. (See console logs!)

See the Pen Vanilla JavaScript palindrome checker in 3 lines by Chris Bongers (@rebelchris) on CodePen.

JavaScript palindrome function

To create our function we define a function that accepts one argument, a string.

function palindrome(string) {
  // Code here
}

Then we need to convert our input string to lowercase and remove all whitespace.

const original = string.replace(/\s/g, '').toLowerCase();

We are using a regular expression to remove all whitespaces.

The next step is to get the reverse of our string. We split every character, reverse the array, and rejoin that array in reversed order.

const reverse = original.split('').reverse().join('');

The last step is to check if they are equal.

return original === reverse;

The whole function will look like this.

function palindrome(string) {
  const original = string.replace(/\s/g, '').toLowerCase();
  const reverse = original.split('').reverse().join('');
  return original === reverse;
}

Awesome, let’s see how it works in action.

console.log(palindrome('Mom')); // True
console.log(palindrome('A nut for a jar of tuna')); // True
console.log(palindrome('Not a palindrome')); // False
console.log(palindrome('Taco cat')); // True
console.log(palindrome('Yo banana boy')); // True

Great stuff, we now have a palindrome checker in JavaScript!

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter