JavaScript Palindrome challenge tutorial

JavaScript Palindromes Challenge: How to Solve It Efficiently

Introduction

In programming, the Palindrome function checks if a given string is a palindrome or not. A palindrome is a word or sentence that reads the same way forward and backward, regardless of punctuation, case, and spacing. To check for palindromes, we need to remove all non-alphanumeric characters such as punctuation, spaces, and symbols, and convert everything to the same case (either lower or upper case). If the string is a palindrome, the function should return true, otherwise, it should return false.

Examples:

  • The word sosis a palindrome because it reads the same backward as forward sos
  • The word _sos is also a palindrome because we ignore/remove non-alphanumeric characters sos
  • The word Madam in Eden, I'm Adam is palindromes because it is the same as backward as forward.

Remember: There are numerous ways to solve specific coding challenges in programming, but we will explore some of them here.

Breaking Down the Problem:

Let's consider the phrase Madam in Eden, I'm Adam. If we remove all the spaces and special characters and convert everything to lowercase, we get madaminedenimadam. Now, we need to check if all the characters in this new string are the same as in the original phrase.

JavaScript

copy

let str = Madam in Eden, I'm Adam;

Then we remove all the spaces and special characters and convert everything into lowercase.

JavaScript

copy

 let str1 = str.toLowerCase().replace(/[^a-z0-9]+/g, "");

We've removed unwanted characters and converted everything to lowercase. Now, let's reverse the string to determine if it's a palindrome or not."

Now, we will reverse the string by using for loop. Before doing so we have to create an empty Array so that we can push our reverse string in that and later on we have to convert that Array into a string for checking if both strings are palindromes or not.

JavaScript

copy

 let reverseArray = [];

 for(let i = str1.length  - 1; i >= 0; i--) {
    reverseArray.push(str1[i])
 }

Since now we have an array of reverse strings, it’s time to convert this array back to string because we can’t directly apply if/else coding for checking two values.

JavaScript

copy

let str2 = reverseArray.join('')

Now, we have successfully converted our reverseArray into the string. Now we can apply the if/else condition so that we can check whether it is palindromes or not.

JavaScript

copy

if(str1 == str2) {
  return true;
} else {
  return false;
}

Complete Function of Palindrome:

JavaScript

copy

let str = 'sos';

function palindrome(str) {

let str1 = str.toLowerCase().replace(/[^a-z0-9]+/g, "");
let reverseArray = [];

for(let i = str1.length  - 1; i >= 0; i--) {
 reverseArray.push(str1[i]);
}

let str2 = reverseArray.join('');

if(str1 == str2) {
  return true;
} else {
  return false;
}

}

console.log(palindrome(str)); // output true 

All Coding Challenges