Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The Palindrome Problem
2.1.
Palindrome Algorithm
2.2.
Example
2.3.
JavaScript
3.
Check Palindrome String Using Built-in Functions
3.1.
Using split(), reverse(), and join() methods:
3.2.
JavaScript
4.
Check if a Number is a Palindrome in JavaScript
4.1.
JavaScript
5.
Checking Palindrome Using Recursion
5.1.
JavaScript
5.2.
Check Whether the Entered String is Palindrome or Not in JavaScript
5.3.
JavaScript
6.
Frequently Asked Questions
6.1.
What is palindrome JavaScript?
6.2.
What is the palindrome function?
6.3.
How to check palindrome substring in JavaScript?
6.4.
How do you check if two strings are palindromes in JavaScript?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Palindrome JavaScript

Author Gaurav Gandhi
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

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.");

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Check Palindrome String Using Built-in Functions

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


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!"));

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);

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);

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");

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?

In JavaScript, a palindrome function checks 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.

What is the palindrome function?

The palindrome function is a programming utility that checks whether a given input (usually a string or a number) is a palindrome. It works by comparing the input with its reverse to see if they are identical. If they match, the function returns a positive result (often accurate), indicating the input is a palindrome; otherwise, it returns a negative result (typically false). This function is widely used in various programming contexts for string validation, data analysis, and algorithmic challenges.

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 Coding Ninjas. 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.

Previous article
Math Random Javascript
Next article
Lodash _.chunk() Method
Live masterclass