Table of contents
1.
The Palindrome Problem
2.
Palindrome Algorithm
3.
Example
3.1.
JavaScript
4.
Check Palindrome String Using Built-in Functions
4.1.
Using split(), reverse(), and join() methods
4.2.
JavaScript
5.
Check if a Number is a Palindrome in JavaScript
5.1.
JavaScript
6.
Checking Palindrome Using Recursion
6.1.
JavaScript
6.2.
Check Whether the Entered String is Palindrome or Not in JavaScript
6.3.
JavaScript
7.
Frequently Asked Questions
7.1.
What is palindrome JavaScript?
7.2.
How to reverse a palindrome in JavaScript?
7.3.
How to check palindrome substring in JavaScript?
7.4.
How do you check if two strings are palindromes in JavaScript?
8.
Conclusion
Last Updated: Jun 28, 2024
Easy

Palindrome JavaScript

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

A palindrome is a fascinating concept you might have come across. Simply put, it reads the same both ways - forward and backward. This can be a word, number, or even a phrase. What's interesting is how it ignores spaces, punctuation, and even capitalization, focusing only on the sequence of characters. Whether a single word or a long sentence, as long as the sequence mirrors itself when reversed, it's a palindrome. This concept is not just limited to literature but also finds relevance in numbers and various sequences in computational fields.

Palindrome javascript

In this article, we will explore various methods to check for palindromes in JavaScript, providing step-by-step algorithms and working code examples.

The Palindrome Problem

The palindrome problem is a classic algorithmic challenge that involves determining whether a given sequence of characters is a palindrome. This problem is not only a popular interview question but also a good exercise in understanding string manipulation and algorithm design.

Palindrome Algorithm

The Palindrome Algorithm compares the beginning and end of a string or number sequence to check for symmetry. It typically iterates from both ends towards the middle, comparing corresponding elements. If all matched pairs are equal, the sequence is a palindrome. This process is often implemented with a loop or recursion in programming. It's essential in various applications to identify palindromic sequences or validate symmetric data structures, including data validation, computational biology, and cryptography.

To check if a string is a palindrome, we follow these steps:

  • Normalize the string: Remove any non-alphanumeric characters and convert all letters to the same case.
     
  • Compare characters: Check if the first character is the same as the last, the second the same as the second to last, and so on.
     
  • Determine the result: If all the corresponding characters match, it's a palindrome.

Example

Check the Palindrome number and string by Accepting the Number through the Prompt Box

  • JavaScript

JavaScript

function isPalindrome(str) {

 str = str.replace(/[\W_]/g, '').toLowerCase();

 let left = 0;

 let right = str.length - 1;

 while (left < right) {

   if (str[left] !== str[right]) {

     return false;

   }

   left++;

   right--;

 }

 return true;

}



// Accept input from the user

const userInput = prompt("Enter a string or number:");

alert(isPalindrome(userInput) ? "It's a palindrome!" : "Not a palindrome.");
You can also try this code with Online Javascript Compiler
Run Code

Output 

output
output

Explanation: This code first normalizes the input by removing non-alphanumeric characters and converting it to lowercase. It then checks each character from the start and end, moving towards the center. If all characters match, it alerts the user that the input is a palindrome.

Check Palindrome String Using Built-in Functions

Using split(), reverse(), and join() methods

The split() method splits a string into an array of substrings based on a specified separator, reverse() reverses the order of the elements in an array, and join() merges all the elements of an array into a string.

Here's how you can use them to check if a string is a palindrome:

  • JavaScript

JavaScript

function isPalindrome(str) {

 // Remove non-alphanumeric characters and convert to lowercase

 const cleanedStr = str.replace(/[\W_]/g, '').toLowerCase();



 // Split the string into an array, reverse it, and join it back into a string

 const reversedStr = cleanedStr.split('').reverse().join('');



 // Check if the reversed string is equal to the original cleaned string

 return reversedStr === cleanedStr;

}


// Example usage:

console.log(isPalindrome("Madam, I'm Adam"));

console.log(isPalindrome("Hello, World!"));
You can also try this code with Online Javascript Compiler
Run Code

Output 

output

Explanation of the code:

str.replace(/[\W_]/g, '').toLowerCase();


This part cleans the input string by removing any characters that are not letters or numbers (denoted by \W which stands for non-word characters) and converting all letters to lowercase for case-insensitive comparison.

cleanedStr.split('');


The split('') method is used to split the cleaned string into an array of individual characters.

reversedStr.reverse();


The reverse() method reverses the array of characters in place.

reversedStr.join('');


The join('') method joins the reversed array of characters back into a single string.

return reversedStr === cleanedStr;

Finally, the function returns true if the reversed string is the same as the cleaned original string, indicating that the input is a palindrome.

Check if a Number is a Palindrome in JavaScript

  • JavaScript

JavaScript

function isNumberPalindrome(number) {

 const strNum = number.toString();

 return strNum === strNum.split('').reverse().join('');

}


// Example usage:

const numberResult = isNumberPalindrome(12321);

console.log(numberResult);
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation: This function converts the number to a string and then applies the same logic as the previous string palindrome check.

Checking Palindrome Using Recursion

  • JavaScript

JavaScript

function isPalindromeRecursive(str, left = 0) {

 let right = str.length - 1 - left;

 return left >= right ? true : str[left] === str[right] && isPalindromeRecursive(str, left + 1);

}

// Example usage:
const recursiveResult = isPalindromeRecursive("racecar");
console.log(recursiveResult);
You can also try this code with Online Javascript Compiler
Run Code

Output

output

Explanation: The recursive function compares the outer characters and calls itself with the next inner pair until it either finds a mismatch or checks all character pairs.

Check Whether the Entered String is Palindrome or Not in JavaScript

  • JavaScript

JavaScript

function checkEnteredPalindrome(str) {

 str = str.replace(/[\W_]/g, '').toLowerCase();
 let isPalin = true;
 for (let i = 0; i < str.length / 2; i++) {

   if (str[i] !== str[str.length - 1 - i]) {
     isPalin = false;

     break;

   }

 }

 return isPalin;

}


// Example usage:

const enteredString = prompt("Enter the string to check:");

alert(checkEnteredPalindrome(enteredString) ? "Palindrome" : "Not a palindrome");
You can also try this code with Online Javascript Compiler
Run Code

Output 

output

Explanation: This function iterates over half of the string, comparing characters from the front and back. If a mismatch is found, it breaks the loop and returns false.

Also read palindrome number in python.

Frequently Asked Questions

What is palindrome JavaScript?

Palindrome Javascript is a function to check whether a given string or number reads the same forwards and backward. It typically involves converting the input to a string and then comparing it with its reversed version. The function returns true if the input is a palindrome and false otherwise. This function is commonly used for string manipulations and validations in JavaScript applications.

How to reverse a palindrome in JavaScript?

To reverse a palindrome in JavaScript, convert the string to an array using split(), reverse the array with reverse(), and join the elements back into a string using join(). The reversed string will be identical to the original palindrome.

How to check palindrome substring in JavaScript?

To check for palindrome substrings in JavaScript, you can write a function that iterates through the string, using a nested loop to generate all possible substrings. For each substring, check if it's a palindrome by comparing it with its reversed version. If a substring is a palindrome, you can process it as needed (like counting, storing, or returning it). This method involves checking each substring, which could be computationally intensive for longer strings.

How do you check if two strings are palindromes in JavaScript?

To check if two strings are palindromes in JavaScript, you can create a function that reverses each string and then compares each reversed string to its original. If both strings match their reversed versions, then both are palindromes. This function would typically involve converting the strings to arrays, reversing them, and then comparing the joined reversed arrays to the original strings. If both comparisons return true, then both strings are palindromes.

Conclusion

Palindromes are a fascinating concept in both literature and coding. In JavaScript, checking for palindromes is a task that can be approached in various ways, each with its own advantages. Whether you're using loops, built-in functions, or recursion, the core principles remain the same: normalize the string and compare characters from both ends.
You can refer to our guided paths on the Code 360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass