Palindrome in JavaScript

In this section, we will explore the concept of Palindrome and verify whether the provided strings or numbers qualify as Palindrome in JavaScript.

A palindrome is defined as a sequence of numbers, letters, or strings that reads identically from both left to right and right to left, thus matching the same characters or preserving the same sequence of characters. In essence, when a sequence of numbers, strings, or characters is reversed and yields the same outcome as the original sequence, it qualifies as a palindrome. Consider the examples of NITIN, 123454321, and madam. Take the word madam, for instance; when we examine this term from both the beginning and the end, it produces the same string. Hence, we can categorize this string or number as a palindrome.

Palindrome Algorithm

Following are the steps to get the Palindrome in JavaScript , as follow:

  • Get the strings or numbers from the user.
  • Take a temporary variable that holds the numbers.
  • Reverse the given number.
  • Compare the original number with the reversed number
  • If the temporary and original number are same, it the number or string is a Palindrome.
  • Else the given string or number is not the Palindrome.
  • Check Palindrome number and string by accepting the number through prompt box.

string.html

Example

<html>

<head> <title> JavaScript Palindrome </title>

</head>

<body>



<!-- Use JavaScript programming code to validate the Palindrome numbers or strings. -->

<script>		

		

function validatePalin(str) {



    // get the total length of the words

    const len = string.length;



    // Use for loop to divide the words into 2 half

    for (let i = 0; i < len / 2; i++) {



        // validate the first and last characters are same

        if (string[i] !== string[len - 1 - i]) {

            alert( 'It is not a palindrome');

        }

    }

    alert( 'It is a palindrome');

}



// accept the string or number from the prompt

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



const value = validatePalin(string);



console.log(value);

</script>

	</body>

		</html>

Output

Upon executing the code provided above, the following image is displayed:

At this stage, we will input either a number or a string in the prompt alert box and subsequently click the OK button to check whether the provided string is a palindrome or not.

After that, it shows the below Output.

In the event that the provided string does not qualify as a Palindrome, it indicates that the string is not a Palindrome. Likewise, we have the ability to input a number and verify if that specified number is also a Palindrome.

Check Palindrome string using built-in Functions

In this tutorial, we will utilize several built-in functions such as the split method, reverse method, and join method to determine whether a number or string is a Palindrome. Let’s examine a JavaScript program that employs these built-in functions to identify the Palindrome of a specified number.

Program2.html

Example

<html>

<head> <title> JavaScript Palindrome </title>

</head>

<body>



<!-- Use JavaScript programming code to validate the Palindrome numbers or strings. -->

<script>			

function palindromeFun (str )

{

// convert the string into an array using the string.split() function

const arrValue = string.split (''); // 



// use reverse() method to reverse the array values

const reveArrVal = arrValue.reverse(); 



// use join() method to group the array values into the string

const revString = reveArrVal.join('');



if (string == revString) // if string condition is equal to the revString

{

alert('It is a Palindrome string '); // print the Palindrome 

}

else {

alert (' It is not a Palindrome string' ); // if the condition is not true.

}

}

// take a string from the user

const string = prompt( ' Enter the string to check Palindrome ');

const value = palindromeFun (string); // call the function

console.log(value);

</script>

	</body>

		</html>

Output

Upon executing the code mentioned above, the following image is displayed:

In the images provided above, we input the string MADAM and subsequently clicked the OK button to verify whether the entered string is a Palindrome.

After that, it shows the below image:

Following are the built-in function to check the palindrome in JavaScript.

  • The split (' ') function is used to convert the string into the individual array characters. const arrayChar = string.split( ' '); // ["A", "P", "P", "L", "E"]
  • A reverse function helps to reverse the position of the individual array characters. const reverseArray = arrayChar.reverse ; // ["E", "L", "P", "P", "A"]
  • The join method is used to combine the individual array characters into the string. const reverseString = reverseArray.Join (' '); // return string is: "ELPPA"
  • Check the Palindrome Number in JavaScript

Let’s develop a JavaScript program that verifies if the input number is a Palindrome.

Str.html

Example

<!Doctype html>

<html lang = "en">



<head>

	<title> Palindrome Program in JavaScript </title>

	<style>

	h1 {

	text-align: center;

	padding: 30px;

	background-color: skyblue;

	color: white;

	}

	

	.palindrome {

	margin: auto;

	width: 40%;

	border: 3px solid gray;

	border-radius: 5px;

	padding: 30px;

	}

	

	#palindrome {

	width: 100%;

	border: 3px solid gray;

	border-radius: 5px;

	padding: 6px;

	}

	</style>

	

	</head>

	

	<body>

		<h1> Palindrome Program in JavaScript </h1>

		<div class="palindrome">

		<label> Enter any string or number : </label> <br> <br>

		<input id= "palindrome"> <br> <br>

		<button type = "button" onclick = "palindrome()" > Check </button>

		</div>

		</body>

		</html>

		

		<script>

		function palindrome() {

		var a, b, no, temp = 0;

		no = Number(document.getElementById ("palindrome").value);

		b = no;

		while (no > 0)

		{

		a = no % 10;

		no = parseInt( no / 10);

		temp = temp*10 + a;

		}

		if (temp == b)

		{

		alert( "It is a Palindrome Number");

		}

		else

		{

		alert ("it is not a Palindrome Number");

		}

		}

		</script>

Output

Upon executing the aforementioned programming code, it produces the following images:

We input the digits and then press the Check button to verify whether the entered number is a Palindrome, as illustrated below.

In the image provided, it indicates that "This is a Palindrome Number." Conversely, if the number obtained by reversing the digits does not match the original number, it signifies that the number entered is not a Palindrome.

Check the Palindrome String in JavaScript

Let's develop a JavaScript program that verifies if the provided string is a Palindrome.

Str2.html

Example

<html>

<head>

<title> Palindrome Program in JavaScript </title>



<style>

	h1 {

	text-align: center;

	padding: 30px;

	background-color: skyblue;

	color: white;

	}

	

	.palin {

	margin: 30px;

	width: 80%;

	border: 3px solid gray;

	border-radius: 5px;

	padding: 30px;

	}

	



	#pa2 {

	

	width: 50%;

	border: 3px solid gray;

	border-radius: 5px;

	padding: 10px;

	}

	

	</style>



</head>

<body>



		<h1> Palindrome Program in JavaScript </h1>

		<div class="palin">

		<label> Enter any string : </label> 

		<input type "text" id= "pa"> <br> <br>

		<label> Resultant string : </label> 

		 <input type = "text" id = "pa2" > </b> <br> 

		<input type= "submit" onclick = "palindrome()" > <br> 

		

		</div>

		

		

		

		<script type = "text/javascript">

		function palindrome()

		{

		var a= document.getElementById("pa").value;

		var b = "";

		for (i = a.length-1; i >= 0; i--)

		{

		b = b + a[i]

		}

		if (a == b)

		document.getElementById("pa2"). value = b + " is a Palindrome String ";

		else

		document.getElementById("pa2"). value = b + " is not a Palindrome String";

		}

		</script>

		</body>

		</html>

Output

Upon execution of the aforementioned programming code, the following image is produced:

We input the string " MADAM " and subsequently pressed the Submit button in the output displayed above. The result shown below appears as follows:

Code Explanation: When the string "MADAM" is input into the text box and the Submit button is clicked, the original string "MADAM" is reversed. Subsequently, each character of the reversed string is compared to the corresponding character in the original string. If both strings match, it indicates that "It is a Palindrome String."

In the output presented above, when the string "JOHN" was inputted, it indicates that the string is not a Palindrome. This conclusion is drawn from the fact that the characters of the string do not correspond with its reversed version.

Input Required

This code uses input(). Please provide values below: