Introduction à Palindrome en JavaScript

De manière générale, Palindrome est un mot tel que lorsque nous lisons ce mot caractère par caractère de l'avant, il correspond exactement à un mot formé lorsque le même mot est lu de l'arrière. Par exemple: «niveau», «madame» etc. Ici, lorsque le mot «niveau» est écrit de l'arrière, le mot final formé sera également «niveau». Ces types de mots, de nombres, de chaînes ou de séries de caractères sont écrits par n'importe quel langage informatique. Ensuite, une telle fonctionnalité est appelée palindrome. Dans le langage du programmeur, le palindrome est une série de caractères, des nombres qui ne changent pas même lorsqu'ils sont écrits dans le sens inverse pour former un mot réarrangé. JavaScript fournit diverses fonctions intégrées pour réaliser cette fonctionnalité. On peut aussi avoir des boucles pour obtenir le même résultat. Nous allons explorer davantage Palindrome dans le langage de programmation côté client JavaScript dans cet article.

Explication logique du Palindrome en JavaScript

Ci-dessous, l'extrait de code utilisant des fonctions intégrées de javaScript pour vous expliquer la logique derrière la chaîne palindrome:

La fonction PTest () est définie dans laquelle nous enverrons la chaîne qui doit être testée pour la fonctionnalité palindrome. Dans le cas où la chaîne est palindrome, nous devrions recevoir un texte en sortie confirmant la même chose, sinon vice versa. La fonction est appelée à la fin après la définition de la fonction. Ici, reverse (), split (), join (), replace (), toLowerCase () sont des fonctions intégrées.

  • Replace (): Cette fonction remplacera les caractères spéciaux et les espaces de la chaîne.
  • toLowerCase (): Cette fonction minuscule la chaîne entière.
  • Split (): la fonction Split divisera la chaîne en caractères individuels.
  • Reverse (): la fonction Reverse inversera la chaîne qui est sortie de la fonction ci-dessus. Cela signifie que la chaîne commencera à partir du dernier caractère lisant caractère par caractère jusqu'au premier caractère.
  • Join (): la fonction Join joindra les caractères qui ont été sortis en sens inverse à partir de la fonction ci-dessus.

Code:

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 fonction palindrome peut également être écrite à l'aide de boucles

Dans le code ci-dessous, la boucle for est utilisée pour parcourir la boucle. En cela, chaque fois que la boucle a exécuté le personnage de l'avant est comparé au personnage de l'arrière. S'ils correspondent, la fonction renverra Boolean true. Cette boucle continuera de s'exécuter jusqu'à la moitié de la longueur de la chaîne d'entrée. Parce que lorsque nous comparons les caractères avant et arrière de la chaîne, nous n'avons pas besoin de parcourir la chaîne complète. La comparaison de la première moitié avec la dernière moitié de la chaîne donnera le résultat. Cela rend le programme plus efficace et plus rapide.

Code:

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 sortie de ce programme donnera true si la chaîne d'entrée de ce programme est un palindrome.

Exemple pour vérifier si la chaîne / le nombre est Palindrome

Vous trouverez ci-dessous le code détaillé en javaScript dans un formulaire HTML pour imprimer si la chaîne est un palindrome ou non.

Code:



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:

Production:

Conclusion

Par conséquent, Palindrome est un concept crucial enseigné aux chercheurs de connaissances dans tous les langages de programmation. Que ce soit C, PHP, C ++, Python, Java ou tout autre langage de programmation, par exemple, tous les langages ont les fonctions de base dans leur bibliothèque standard pour prendre en charge palindrome. Dans le cas où il n'y a pas de fonction à prendre en charge, nous pouvons toujours avoir des boucles comme while, for ou contrôler des structures comme If, ​​else, break instructions pour réaliser cette fonctionnalité.

Articles recommandés

Ceci est un guide de Palindrome en JavaScript. Nous discutons ici de l'explication logique avec un exemple pour vérifier si la chaîne / le nombre est un palindrome. Vous pouvez également consulter les articles suivants pour en savoir plus -

  1. Fonctions mathématiques JavaScript
  2. Expressions régulières en JavaScript
  3. Cadres JavaScript MVC
  4. Fusionner le tri en JavaScript
  5. jQuery querySelector | Exemples pour querySelector
  6. Boucles dans VBScript avec des exemples
  7. Expressions régulières en Java
  8. Exemples de fonctions intégrées Python