Въведение в Palindrome в JavaScript

В общ смисъл, Palindrome е дума като тази, когато ние четем този символ на символ по знак отпред, съвпада точно с дума, образувана, когато една и съща дума се чете отзад. Например: "ниво", "госпожо" и т.н. Тук, когато думата "ниво" е написана отзад, тогава и финалната дума ще бъде "ниво". Тези видове думи, цифри, низ или серия от знаци, когато са написани от всеки компютърен език. Тогава такава функционалност се нарича палиндром. В езика на програмиста палиндромът е поредица от знаци, числа, които не се променят дори когато е написана от обратна посока, образувайки пренаредена дума. JavaScript предоставя различни вградени функции за реализиране на тази функционалност. Можем да имаме и бримки, за да получим същия резултат. В тази статия ще проучим повече за палиндром в езика за програмиране от страна на клиента.

Логическо обяснение на Palindrome в JavaScript

По-долу е фрагментът на кода, използвайки вградени функции на javaScript, за да ви обясни логиката зад низ на палиндром:

Функцията PTest () е дефинирана, в която ще изпратим низ, който трябва да бъде тестван за функционалност на палиндром. В случай, че низът е палиндром, тогава трябва да получим текст в изход, потвърждаващ същото, в противен случай обратното. Функцията се извиква в края след дефиницията на функцията. Тук функциите за реверс (), разделяне (), присъединяване (), замяна (), toLowerCase () са вградени функции.

  • Replace (): Тази функция ще замести специалните символи и интервали от низа.
  • toLowerCase (): Тази функция ще замени малки букви на целия низ.
  • Разделяне (): Сплит функцията ще раздели низа на отделни знаци.
  • Reverse (): Обратната функция ще обърне низ, който се извежда от горната функция. Това означава, че низът ще започва от последния символ за четене на символ по символ до първия символ.
  • Join (): Функцията за присъединяване ще се присъедини към героите, които са били изведени по обратен начин от горната функция.

Код:

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

Функцията palindrome може да се запише и с помощта на бримки

В кода по-долу за цикъл се използва за повторение през цикъла. При това всеки път, когато цикълът е изпълнил символа отпред, се сравнява с символа от задната страна. Ако те съвпадат, функцията ще върне Boolean вярно. Този цикъл ще продължи да изпълнява до половината от дължината на входния низ. Защото когато сравняваме предните и задните символи на низа, тогава няма нужда да повторяме през целия низ. Сравняването на първото полувреме с последната половина на низа ще даде резултат. Това прави програмното пространство ефективно и по-бързо.

Код:

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

Резултатът от тази програма ще даде истина, ако входният низ на тази програма е палиндром.

Пример за проверка дали низът / числото е палиндром

По-долу е подробният код в javaScript във формата на HTML за отпечатване, ако низът е палиндром или не.

Код:



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:

изход:

заключение

Следователно Palindrome е ключова концепция, преподавана на търсещите знания на всички програмни езици. Независимо дали е C, PHP, C ++, Python, Java или друг език за програмиране, например, всички езици имат основните функции в стандартната си библиотека за поддържане на палиндром. В случай, че няма функция за поддръжка, винаги можем да имаме цикли като while, за или да контролираме структури като If, else, прекъсваме оператори, за да реализираме тази функционалност.

Препоръчителни статии

Това е ръководство за Palindrome в JavaScript. Тук обсъждаме логичното обяснение с пример, за да проверим дали низът / числото е палиндром. Можете също да разгледате следните статии, за да научите повече -

  1. JavaScript математически функции
  2. Редовни изрази в JavaScript
  3. JavaScript MVC рамки
  4. Сливане Сортиране в JavaScript
  5. jQuery querySelector | Примери за querySelector
  6. Цикли в VBScript с примери
  7. Редовни изрази в Java
  8. Примери за вградени функции на Python