A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.
In this tutorial, we will write a JavaScript program to check whether a given string is a palindrome or not.
To solve this problem, we need to compare the string with its reverse. If the original string and its reverse are the same, then the string is a palindrome.
Here’s the JavaScript program to check whether a given string is a palindrome or not:
function isPalindrome(str) { // Remove non-alphanumeric characters and convert to lowercase str = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); // Compare the string with its reverse return str === str.split('').reverse().join(''); }
Let’s break down the above code. The isPalindrome() function takes a string str as input and returns true if str is a palindrome and false otherwise.
First, we remove all non-alphanumeric characters from the string and convert it to lowercase. We do this to ignore any spaces, punctuation, or casing differences in the input string.
Next, we compare the string with its reverse. To do this, we split the string into an array of characters, reverse the array, and join the characters back into a string.
If the resulting string is the same as the original string, then the input string is a palindrome.
Here are some examples of how to use the isPalindrome() function:
console.log(isPalindrome('racecar')); // true console.log(isPalindrome('A man, a plan, a canal: Panama')); // true console.log(isPalindrome('hello world')); // false
In conclusion, we can easily check whether a given string is a palindrome or not using JavaScript by comparing the string with its reverse. The code is simple and easy to understand.