Introducción a Palindrome en JavaScript

En sentido general, Palíndromo es una palabra como la que cuando leemos esa palabra carácter por carácter de adelante, coincide exactamente con una palabra formada cuando la misma palabra se lee de atrás. Por ejemplo: "nivel", "señora", etc. Aquí, cuando la palabra "nivel" se escribe desde atrás, también la palabra final formada será "nivel". Este tipo de palabras, números, cadenas o series de caracteres cuando están escritos por cualquier lenguaje de computadora. Entonces tal funcionalidad se llama palíndromo. En el lenguaje del programador, el palíndromo es una serie de caracteres, números que no cambian incluso cuando se escribe desde la dirección inversa formando una palabra reordenada. JavaScript proporciona varias funciones integradas para realizar esta funcionalidad. También podemos tener bucles para obtener el mismo resultado. Vamos a explorar más en palindrome en el lenguaje de programación JavaScript del lado del cliente en este artículo.

Explicación lógica de Palindrome en JavaScript

A continuación se muestra el fragmento de código que utiliza funciones incorporadas de javaScript para explicarle la lógica detrás de la cadena de palíndromo:

La función PTest () está definida en la cual enviaremos la cadena que necesita ser probada para la funcionalidad del palíndromo. En caso de que la cadena sea palíndromo, deberíamos recibir un texto en la salida que confirme lo mismo, de lo contrario, viceversa. La función se llama al final después de la definición de la función. Aquí reverse (), split (), join (), replace (), toLowerCase () son funciones integradas.

  • Reemplazar (): esta función reemplazará los caracteres y espacios especiales de la cadena.
  • toLowerCase (): esta función minúscula toda la cadena.
  • Split (): la función Split dividirá la cadena en caracteres individuales.
  • Reverse (): la función inversa revertirá la cadena que sale de la función anterior. Esto significa que la cadena comenzará desde el último carácter leyendo carácter por carácter hasta el primer carácter.
  • Unir (): la función Unir unirá los caracteres que se obtuvieron de forma inversa a partir de la función anterior.

Código:

Function PTest (TestString) (
var remSpecChar = TestString.replace(/(^A-Z0-9)/ig, "").toLowerCase(); /* this function removes any space, special character and then makes a string of lowercase */
var checkingPalindrome = remSpecChar.split('').reverse().join(''); /* this function reverses the remSpecChar string to compare it with original inputted string */
if(remSpecChar === checkingPalindrome)( /* Here we are checking if TestString is a Palindrome sring or not */
document.write(" "+ myString + " is a Palindrome string "); /* Here we write the string to output screen if it is a palindrome string */
)
else(
document.write(" " + myString + " is not a Palindrome string "); /* Here we write the string to output screen if it is not a palindrome string */
)
)
PTest('"Hello"') /* Here we are calling the above function with the test string passed as a parameter. This function's definition is provided before function calling itself so that it is available for the compiler before actual function call*/
PTest('"Palindrome"')
PTest('"7, 1, 7"') /* This is a Palindrome string */

La función palíndromo también se puede escribir usando bucles

En el siguiente código, el bucle for se usa para iterar a través del bucle. En esto, cada vez que el bucle se ha ejecutado, el personaje desde el frente se compara con el personaje en la parte trasera. Si coinciden, la función devolverá Boolean verdadero. Este bucle seguirá ejecutándose hasta la mitad de la longitud de la cadena de entrada. Porque cuando comparamos los caracteres delantero y trasero de la cadena, no necesitamos iterar a través de la cadena completa. La comparación de la primera mitad con la última mitad de la cadena dará el resultado. Esto hace que el programa ahorre espacio y sea más rápido.

Código:

function Findpalindrome(TestStr) (
var PlainStr= TestStr.replace(/(^0-9a-z)/gi, '').toLowerCase().split("");
for(var i=0; i < (PlainStr.length)/2; i++)(
if(PlainStr(i) == PlainStr(PlainStr.length-i-1))(
return true;
) else
return false;
)
) Findpalindrome("ta11at");

La salida de este programa dará verdadero si la cadena de entrada de este programa es un palíndromo.

Ejemplo para verificar si la cadena / número es palíndromo

A continuación se muestra el código detallado en javaScript dentro de un formulario HTML para imprimir si la cadena es un palíndromo o no.

Código:



Palindrome using JS
input(
padding: 20px;
)

function TestFunction()
(
//Here we are getting the value from the textbox on browser
var InputStr = document.getElementById('tbox').value; //here we are calling checkingPalindrome() function and passing a string into it
var resStr = checkingPalindrome(InputStr);
alert('The input string "'+InputStr+'" is "'+resStr+'"'); // This will allow a //rectangular box to be popped up on the screen to display result
)
function checkingPalindrome(InputStr)
(
var origString;
//here we are converting the string into a lowercase string
InputStr = InputStr.toLowerCase();
//here we are storing the InputStr in origString for reference
origString= InputStr;
//here we are reversing the entered string
InputStr = InputStr.split(''); //this function will split the input string
InputStr = InputStr.reverse(); //this function will reverse the string
InputStr = InputStr.join(''); //this function will join the reversed string characters
var revString = InputStr;
//here we are checking if both the input string and the reversed string are same
//and based on it the string will be declared palindrome or not
if(origString == revString)(
return 'Palindrome string'; // this will return "Palindrome" if true //otherwise control will flow to else condition
)
else
(
return 'not a Palindrome string';
)
)


Javascript Program to find if the number is Palindrome or not:



Palindrome using JS
input(
padding: 20px;
)

function TestFunction()
(
//Here we are getting the value from the textbox on browser
var InputStr = document.getElementById('tbox').value; //here we are calling checkingPalindrome() function and passing a string into it
var resStr = checkingPalindrome(InputStr);
alert('The input string "'+InputStr+'" is "'+resStr+'"'); // This will allow a //rectangular box to be popped up on the screen to display result
)
function checkingPalindrome(InputStr)
(
var origString;
//here we are converting the string into a lowercase string
InputStr = InputStr.toLowerCase();
//here we are storing the InputStr in origString for reference
origString= InputStr;
//here we are reversing the entered string
InputStr = InputStr.split(''); //this function will split the input string
InputStr = InputStr.reverse(); //this function will reverse the string
InputStr = InputStr.join(''); //this function will join the reversed string characters
var revString = InputStr;
//here we are checking if both the input string and the reversed string are same
//and based on it the string will be declared palindrome or not
if(origString == revString)(
return 'Palindrome string'; // this will return "Palindrome" if true //otherwise control will flow to else condition
)
else
(
return 'not a Palindrome string';
)
)


Javascript Program to find if the number is Palindrome or not:



Palindrome using JS
input(
padding: 20px;
)

function TestFunction()
(
//Here we are getting the value from the textbox on browser
var InputStr = document.getElementById('tbox').value; //here we are calling checkingPalindrome() function and passing a string into it
var resStr = checkingPalindrome(InputStr);
alert('The input string "'+InputStr+'" is "'+resStr+'"'); // This will allow a //rectangular box to be popped up on the screen to display result
)
function checkingPalindrome(InputStr)
(
var origString;
//here we are converting the string into a lowercase string
InputStr = InputStr.toLowerCase();
//here we are storing the InputStr in origString for reference
origString= InputStr;
//here we are reversing the entered string
InputStr = InputStr.split(''); //this function will split the input string
InputStr = InputStr.reverse(); //this function will reverse the string
InputStr = InputStr.join(''); //this function will join the reversed string characters
var revString = InputStr;
//here we are checking if both the input string and the reversed string are same
//and based on it the string will be declared palindrome or not
if(origString == revString)(
return 'Palindrome string'; // this will return "Palindrome" if true //otherwise control will flow to else condition
)
else
(
return 'not a Palindrome string';
)
)


Javascript Program to find if the number is Palindrome or not:

Salida:

Conclusión

Por lo tanto, Palindrome es un concepto crucial que se enseña a los buscadores de conocimiento en todos los lenguajes de programación. Ya sea C, PHP, C ++, Python, Java o cualquier otro lenguaje de programación, por ejemplo, todos los lenguajes tienen las funciones básicas en su biblioteca estándar para soportar palíndromo. En caso de que no haya una función que admitir, siempre podemos tener bucles como while, for o controlar estructuras como If, de lo contrario, romper declaraciones para realizar esta funcionalidad.

Artículos recomendados

Esta es una guía de Palindrome en JavaScript. Aquí discutimos la explicación lógica con un ejemplo para verificar si la cadena / número es un palíndromo. También puede consultar los siguientes artículos para obtener más información:

  1. Funciones matemáticas de JavaScript
  2. Expresiones regulares en JavaScript
  3. JavaScript MVC Frameworks
  4. Combinar Ordenar en JavaScript
  5. jQuery querySelector | Ejemplos para querySelector
  6. Bucles en VBScript con ejemplos
  7. Expresiones regulares en Java
  8. Ejemplos de funciones integradas de Python