JavaScript: Check if a String is a Palindrome

1. Introduction

A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward (ignoring spaces, punctuation, and capitalization). Examples include "radar", "level", or "madam". In this guide, we'll create a simple JavaScript program to determine if a given string is a palindrome.

2. Program Overview

During this tutorial, we will:

1. Introduce a sample string.

2. Develop a function to check if the string is a palindrome.

3. Display the result.

3. Code Program

let sampleString = "Madam";  // String to be checked
let isPalindrome = false;  // Variable to store the result

// Function to check if a string is a palindrome
function checkPalindrome(str) {
    // Convert the string to lowercase and remove non-alphanumeric characters
    let cleanedString = str.toLowerCase().replace(/[^a-zA-Z0-9]/g, '');
    let reversedString = cleanedString.split('').reverse().join('');
    return cleanedString === reversedString;
}

isPalindrome = checkPalindrome(sampleString);

console.log("Sample String: " + sampleString);
console.log("Is Palindrome? " + isPalindrome);

Output:

Sample String: Madam
Is Palindrome? true

4. Step By Step Explanation

1. Variable Initialization: We begin with our sampleString which we wish to check, and a boolean variable isPalindrome to store the outcome.

2. Palindrome Checking Function: The checkPalindrome(str) function proceeds in distinct steps:

- The string is first converted to lowercase with toLowerCase(), ensuring our check isn't case-sensitive.

- We also remove any non-alphanumeric characters using a regular expression, ensuring punctuations or spaces don't affect the palindrome check.

- Next, we reverse the cleaned string, similar to our string reversal method from earlier.

- We then compare the cleaned original string to the reversed string. If they match, our string is a palindrome.

3. Function Invocation: We call checkPalindrome with our sample string and store the boolean result in isPalindrome.

4. Result Display: The console.log function is then used to present both the sample string and the result of our palindrome check.

Comments