dhairyashah
Portfolio

Dec 22nd, 2022

Javascript program to check Palindrome

Author Picture

Dhairya Shah

Software Engineer

Introduction

In this article, we will learn how to write a function in JavaScript that determines whether a given string is a palindrome or not. A palindrome is a word, phrase, or sequence of characters that reads the same forwards and backwards.

Table of Contents:

  1. Introduction
  2. Understanding Palindromes
  3. Writing the Function in JavaScript
  4. Testing the Function
  5. Improving the Function
  6. Conclusion

Understanding Palindromes

To determine whether a string is a palindrome, we need to compare the string to its reverse. For example, the string “racecar” is a palindrome because it is spelled the same forwards and backwards. The string “hello” is not a palindrome because it is not spelled the same forwards and backwards.

Writing the Function in JavaScript

To write the function, we will follow these steps:

Here is what the function will look like:


function isPalindrome(str) {
  const reversed = str.split('').reverse().join('');
  return str === reversed;
}

Testing the Function

To test the function, we can call it with various strings as arguments and print the result to the console. Here is an example:


console.log(isPalindrome('racecar')); // true
console.log(isPalindrome('hello')); // false
console.log(isPalindrome('level')); // true
console.log(isPalindrome('rotator')); // true
console.log(isPalindrome('civic')); // true

Improving the Function

We can also make the function more robust by adding some additional checks. For example, we can make the function case-insensitive by converting the string to lowercase before comparing it to the reversed string. We can also remove any non-alphanumeric characters from the string before comparing it to the reversed string.

Here is an updated version of the function that includes these additional checks:


function isPalindrome(str) {
  str = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  const reversed = str.split('').reverse().join('');
  return str === reversed;
}

With this function, we can now determine whether a given string is a palindrome or not with greater accuracy and flexibility.

Conclusion

In this article, we learned how to write a function in JavaScript that determines whether a given string is a palindrome or not. By following the steps outlined in this article, you can now easily check whether a string is a palindrome or not using JavaScript.

This article was generated by ChatGPT to demonstrate its capabilities.