DEV Community

Cedric Muuo
Cedric Muuo

Posted on

Checking for a Palindrome using Javascript built-in functions

CHALLENGE

Return 'true' if a word is a palindrome and 'false' if not.

EXPLANATION

What is a Palindrome? It is a word or a sentence that is spelled the same both forward and backward, ignoring the punctuation, casing, and spacing. An example is the word 'Racecar'. To check for a palindrome in Javascript, you will need to remove all non-alphanumeric characters(punctuations, symbols, and spaces)then turn all the letters into lowercase.

In order to remove the non-alphanumeric letters, we shall use a Regular Expression(Regex). Regular Expressions are patterns used to match character combinations in strings. The Regex used to match any non-alpha-numeric characters is '[\W_]' which can be expounded to read '[^A-Za-z0–9]'.

SOLUTION

For this solution, we will use several methods:
a. toLowerCase() which will return all the characters in the string in lowercase.
b. .replace() which will return the replaced string(only alpha-numeric characters) by the Regular Expression we just created.
c. .split() which will split the returned string into and return an array of characters.
d. .reverse() which will reverse the order of the characters in the array.
e. .join() which will join the reversed characters into a string.

Here is the complete code for this:

const str = 'A man, a plan, a canal. Panama';

function palindrome(str) {

//Remove all the non-alphanumerics and turn the string to lowercase

var lowRegStr = str.replace(/[^0-9a-zA-Z]/g, '').toLowerCase();

// Split the returned string, reverse the characters ,join them, and return the reversed string.

var reverseStr = lowRegStr.split('').reverse().join('');
return reverseStr === lowRegStr;
}

console.log(palindrome(str));
Enter fullscreen mode Exit fullscreen mode

This will log 'true' if the string is a palindrome and 'false' if otherwise.

Latest comments (0)