Validate Palindromes with Javascript code

In this post we will know how to validate palindromes with javascript code. Firstly we should begin by explaining, what the term palindrome specifically mean? Well, no more, no less that we can read text or words from left to right as well as from right to left without changing its meaning.

This type of exercise is usually part of the practical tests for javascript students. 

With a little bit of javascript code we will be able to know if a word is a palindrome or not. If this text or word is palindrome, then we will get a message confirming so otherwise the message will confirm that it is not.

With the following code we ask the user to enter a word or term. Once it has been entered a pop up message will confirm it or not. To make it easier to verify what the user has entered, the javascript code does not take into account the spaces between words that may be there.

Javascript code explained step by step

Firstly we create a variable called cadena. In this variable we will see the option prompt. When  the prompt option is used the browser will give us the possibility to insert text into a small pop up. Therefore the information that the user enters in this pop up will be store in the variable cadena. 

Since we do not know if the user will enter uppercase or lowercase letters, we apply the toLowerCase ( ) method . This method converts the entered text to lowercase letters, in case uppercase letters are entered.

With the replace ( ) method, we remove the empty spaces that the text inserted by the user may have.

As a result of those two methods, toLowerCase() and replace(), we are converting what the user has written in text without spaces and in lower case.

This format will help us in the comparison to validate palindromes with javascript code and we avoid the potential “case sensitive” and space errors of letters or names.

We also create another variable called reves. This variable converts the information stored in the variable cadena from right to left.  

After this, we are ready to compare the values of cadena and reves. 

Finally this comparision is carried out by the function palindromo. If the value of both of them matches with each other, we will get a succesful message or alternatively an unseccesful message if it does not match.