Introdução ao Palindrome em JavaScript

Em sentido geral, Palíndromo é uma palavra como a que, quando lemos essa palavra caractere por caractere, a partir de frente, ela corresponde exatamente a uma palavra formada quando a mesma palavra é lida de trás para a frente. Por exemplo: "nível", "senhora" etc. Aqui, quando a palavra "nível" é escrita de trás para frente, também a palavra final formada será "nível". Esses tipos de palavras, números, cadeias ou séries de caracteres são escritos por qualquer linguagem de computador. Então, essa funcionalidade é chamada de palíndromo. No palíndromo da linguagem do programador, há uma série de caracteres, números que não mudam, mesmo quando escritos na direção inversa, formando uma palavra reorganizada. O JavaScript fornece várias funções internas para realizar essa funcionalidade. Também podemos ter loops para obter o mesmo resultado. Neste artigo, exploraremos mais o palíndromo na linguagem de programação JavaScript do lado do cliente.

Explicação lógica do Palindrome em JavaScript

Abaixo está o snippet de código que utiliza funções embutidas do javaScript para explicar a lógica por trás da string do palíndromo:

A função PTest () é definida na qual enviaremos a string que precisa ser testada para a funcionalidade do palíndromo. Caso a string seja palíndromo, devemos receber um texto na saída confirmando o mesmo, caso contrário, vice-versa. A função é chamada no final após a definição da função. Aqui reverse (), split (), join (), replace (), toLowerCase () são funções internas.

  • Substituir (): Esta função substituirá os caracteres e espaços especiais da sequência.
  • toLowerCase (): Esta função irá minúscula a seqüência inteira.
  • Split (): A função Split dividirá a string em caracteres individuais.
  • Reverse (): A função Reverse reverterá a string que é emitida a partir da função acima. Isso significa que a cadeia começará do último caractere lendo caractere por caractere até o primeiro caractere.
  • Join (): A função Join juntará os caracteres que foram produzidos de forma inversa a partir da função acima.

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 */

A função palíndromo também pode ser escrita usando loops

No código abaixo, o loop for é usado para percorrer o loop. Nisto, toda vez que o loop executa o caractere de frente é comparado com o caractere na extremidade traseira. Se eles corresponderem, a função retornará Boolean true. Esse loop continuará em execução até a metade do comprimento da string de entrada. Porque, quando comparamos os caracteres frontal e traseiro da sequência, não precisamos iterar através da sequência completa. Comparar a primeira metade com a última metade da sequência dará o resultado. Isso torna o programa eficiente em termos de espaço e mais 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");

A saída deste programa será verdadeira se a sequência de entrada deste programa for um palíndromo.

Exemplo para verificar se a sequência / número é palíndromo

Abaixo está o código detalhado em javaScript dentro de um formulário HTML para imprimir se a sequência for um palíndromo ou não.

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:

Resultado:

Conclusão

Portanto, o Palindrome é um conceito crucial ensinado aos buscadores de conhecimento em todas as linguagens de programação. Seja C, PHP, C ++, Python, Java ou qualquer outra linguagem de programação, por exemplo, todas as linguagens possuem funções básicas em sua biblioteca padrão para suportar palíndromo. No caso de não haver função para suportar, sempre podemos ter loops como while, para ou controlar estruturas como If, else, quebrar instruções para realizar essa funcionalidade.

Artigos recomendados

Este é um guia para o Palindrome em JavaScript. Aqui discutimos a explicação lógica com um exemplo para verificar se a string / número é um palíndromo. Você também pode consultar os seguintes artigos para saber mais -

  1. Funções matemáticas de JavaScript
  2. Expressões regulares em JavaScript
  3. Frameworks MVC JavaScript
  4. Mesclar Classificar em JavaScript
  5. jQuery querySelector | Exemplos para querySelector
  6. Loops no VBScript com exemplos
  7. Expressões regulares em Java
  8. Exemplos de funções internas do Python