Introduzione a Palindrome in JavaScript

In senso generale, Palindrome è una parola come quella che quando leggiamo quella parola carattere per carattere da avanti, corrisponde esattamente a una parola formata quando la stessa parola viene letta da dietro. Ad esempio: "livello", "signora" ecc. Qui, quando la parola "livello" è scritta all'indietro, anche l'ultima parola formata sarà "livello". Questi tipi di parole, numeri, stringhe o serie di caratteri quando sono scritti da qualsiasi linguaggio del computer. Quindi tale funzionalità viene chiamata palindromo. Nel linguaggio del programmatore palindrome è una serie di caratteri, numeri che non cambiano anche quando è scritto dalla direzione opposta formando una parola riordinata. JavaScript offre varie funzioni integrate per realizzare questa funzionalità. Possiamo anche avere dei loop per ottenere lo stesso risultato. In questo articolo esploreremo di più nel palindromo nel linguaggio di programmazione JavaScript lato client.

Spiegazione logica di Palindrome in JavaScript

Di seguito è riportato lo snippet di codice che utilizza le funzioni integrate di javaScript per spiegare la logica dietro la stringa palindrome:

Viene definita la funzione PTest () in cui invieremo la stringa che deve essere testata per la funzionalità palindromo. Nel caso in cui la stringa sia palindromo, dovremmo ricevere un testo in uscita che confermi lo stesso altrimenti viceversa. La funzione viene chiamata alla fine dopo la definizione della funzione. Qui reverse (), split (), join (), replace (), toLowerCase () sono funzioni integrate.

  • Sostituisci (): questa funzione sostituirà i caratteri e gli spazi speciali della stringa.
  • toLowerCase (): questa funzione minuscola per l'intera stringa.
  • Dividi (): la funzione Dividi divide la stringa in singoli caratteri.
  • Reverse (): la funzione Reverse inverte la stringa emessa dalla funzione precedente. Ciò significa che la stringa inizierà dall'ultimo carattere che legge carattere per carattere fino al primo carattere.
  • Join (): la funzione Join si unirà ai personaggi che sono stati emessi in modo inverso rispetto alla funzione sopra.

Codice:

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 funzione palindromo può anche essere scritta usando loop

Nel codice seguente il ciclo for viene usato per scorrere il ciclo. In questo, ogni volta che il loop ha eseguito il personaggio dalla parte anteriore viene confrontato con il personaggio nella parte posteriore. Se corrispondono, la funzione restituirà il valore booleano true. Questo ciclo continuerà ad essere eseguito fino alla metà della lunghezza della stringa di input. Perché quando confrontiamo i caratteri anteriore e posteriore della stringa, non è necessario scorrere l'intera stringa. Confrontando la prima metà con l'ultima metà della stringa si otterrà il risultato. Ciò rende il programma efficiente in termini di spazio e più veloce.

Codice:

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

L'output di questo programma darà true se la stringa di input di questo programma è un palindromo.

Esempio per verificare se la stringa / numero è palindromo

Di seguito è riportato il codice dettagliato in javaScript all'interno di un modulo HTML da stampare se la stringa è un palindromo o meno.

Codice:



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:

Produzione:

Conclusione

Quindi Palindrome è un concetto cruciale insegnato ai cercatori di conoscenza in tutti i linguaggi di programmazione. Che si tratti di C, PHP, C ++, Python, Java o qualsiasi altro linguaggio di programmazione, ad esempio, tutti i linguaggi hanno le funzioni di base nella loro libreria standard per supportare palindrome. Nel caso in cui non ci sia alcuna funzione da supportare, possiamo sempre avere loop come while, for o control strutture come If, ​​else, istruzioni break per realizzare questa funzionalità.

Articoli consigliati

Questa è una guida a Palindrome in JavaScript. Qui discutiamo la spiegazione logica con un esempio per verificare se la stringa / numero è un palindromo. Puoi anche consultare i seguenti articoli per saperne di più -

  1. Funzioni matematiche JavaScript
  2. Espressioni regolari in JavaScript
  3. JavaScript MVC Frameworks
  4. Unisci ordinamento in JavaScript
  5. jQuery querySelector | Esempi per querySelector
  6. Loop in VBScript con esempi
  7. Espressioni regolari in Java
  8. Esempi di funzioni integrate di Python

Categoria: