TypeScript: 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 forward and backward (ignoring spaces, punctuation, and capitalization). In this blog post, we'll create a TypeScript function to check if a given string is a palindrome.

2. Program Overview

We'll be defining a function named isPalindrome that will take a string as its argument and return a boolean indicating whether the string is a palindrome or not.

3. Code Program

// Function to check if a string is a palindrome
function isPalindrome(str: string): boolean {
    // Convert string to lowercase and remove non-alphanumeric characters
    const cleanStr = str.toLowerCase().replace(/[^a-z0-9]/g, "");

    // Check if cleaned string is equal to its reverse
    return cleanStr === cleanStr.split("").reverse().join("");
}

// Test the function
const testString = "A man, a plan, a canal, Panama";
console.log(`Is "${testString}" a palindrome?`, isPalindrome(testString));

Output:

Is "A man, a plan, a canal, Panama" a palindrome? true

4. Step By Step Explanation

1. First, we define our isPalindrome function which takes a single string argument str.

2. Inside the function, we transform the string to lowercase using toLowerCase(). This ensures our function is case-insensitive.

3. We further clean the string to consider only alphanumeric characters by using a regular expression with the replace method. This step helps in handling strings with spaces, punctuation marks, etc.

4. After cleaning the string, we check if the string is equal to its reversed version. We reverse the string by splitting it into an array of characters with split(""), then reversing the array using reverse(), and finally joining the array back into a string with join("").

5. If the cleaned string and its reversed version are the same, it indicates that the original string is a palindrome, and the function returns true, otherwise false.

6. We then test our function using the famous palindrome phrase "A man, a plan, a canal, Panama" and display the result.

Comments