How To Check for Palindromes in JavaScript

Anastasia Orlova
JavaScript in Plain English
2 min readDec 14, 2020

--

Solving a palindrome algorithm is one of the most common data structure tasks during a technical interview. In this blog, I’m going to break down one of those algorithms and share with you my method of solving it. It might be not the smartest and the most efficient way, so feel free to come up with any other!

First things first: what is a palindrome? It is a sequence of characters that reads the same backward or forward. Our task is to find out whether a given string is a palindrome. Return true if the given string is a palindrome. Otherwise, return false.

So, our first step is to remove all non-alphanumeric characters and turn everything into a lower case in order to check for palindromes. Luckily for us, to complete this task we have two build-in methods.

function findPalindrome(string) {
let cleanChar = string.replace(/[^A-Z0-9]/ig, "").toLowerCase();
}

Our second step is to reverse our “clean” string. In this case, split(), reverse() and join() methods come really handy. The split() method splits a string into an array of strings. The reverse() method reverses an array. The join() method joins all elements of an array back into a string.

function findPalindrome(string) {
let cleanChar = string.replace(/[^A-Z0-9]/ig, "").toLowerCase();
let reversedChar = cleanChar.split('').reverse().join('');
}

Our third and last step is to compare two strings and to check if our string is a Palindrome.

function findPalindrome(string) {
let cleanChar = string.replace(/[^A-Z0-9]/ig, "").toLowerCase();
let reversedChar = cleanChar.split('').reverse().join('');
return (cleanChar === reversedChar)
}

That was my quick guide to solving a palindrome algorithm. Hope it was helpful!

Source:

  1. Two Ways to Check for Palindromes in JavaScript
  2. StackOverflow
  3. 11 ways to check for palindromes in JavaScript

--

--