Увод у Палиндроме у ЈаваСцрипт-у

У општем смислу, Палиндроме је реч таква као што је када читамо ту реч по карактеру унапред, тачно се подудара са речју која је формирана када се иста реч чита уназад. На пример: „ниво“, „мадам“ итд. Овде када се реч „ниво“ напише уназад, тада ће и коначна реч која је формирана бити „ниво“. Ове врсте речи, бројева, низа или низа знакова када их пише било који рачунар. Тада се таква функционалност назива палиндром. На језику програмера палиндроме представља низ знакова, бројева који се не мењају ни када су написани из обрнутог правца, формирајући поново уређену реч. ЈаваСцрипт пружа разне уграђене функције за реализацију ове функционалности. Такође можемо имати петље да добијемо исти резултат. У овом чланку ћемо истражити више палиндрома на програмском језику на страни клијента.

Логичко објашњење Палиндрома у ЈаваСцрипт-у

Испод је исјечак кода помоћу уграђених функција јаваСцрипт-а да би вам објаснио логику иза палиндроме низа:

Дефинисана је функција ПТест () у којој ћемо послати низ који треба тестирати на функцију палиндроме. У случају да је стринг палиндроме, требало би да примимо текст у излазу који потврђује исто, у супротном обрнуто. Функција се позива на крају након дефиниције функције. Овде су уграђене функције реверсе (), сплит (), јоин (), замени (), тоЛоверЦасе ().

  • Замените (): Ова функција ће заменити посебне знакове и размаке из низа.
  • тоЛоверЦасе (): Ова функција ће снизити цијели низ.
  • Сплит (): Сплит функција ће подијелити низ на појединачне знакове.
  • Реверсе (): Реверсе фунцтион ће обрнути стринг који је избачен из горње функције. То значи да ће низ започети од карактера до последњег карактера за читање до првог знака.
  • Јоин (): Функција придруживања придружиће се ликовима који су из горње функције приказани обрнуто.

Шифра:

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

Палиндроме функција се такође може писати помоћу петље

У доњем коду, петља фор користи се за понављање кроз петљу. При томе, сваки пут када се петља изврши, лик са предње стране упоређује се са ликом на задњем крају. Ако се подударају, функција ће вратити Боолеан труе. Ова петља наставиће да се извршава до половине дужине улазног низа. Јер када упоређујемо предње и задње знакове низа, тада нам не треба понављати цео низ. Поређење првог полувремена са последњом половином низа даће резултат. Ово чини програмски простор ефикасним и бржим.

Шифра:

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

Резултат овог програма ће бити тачан ако је улазни низ овог програма палиндром.

Пример за проверу да ли је низ / број Палиндроме

Испод је детаљан код у ЈаваСцрипту у ХТМЛ облику за штампање да ли је низ палиндром или не.

Шифра:



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:

Излаз:

Закључак

Стога је Палиндроме кључни концепт који се подучава трагачима знања на свим програмским језицима. Било да су то Ц, ПХП, Ц ++, Питхон, Јава или било који други програмски језик, на пример, сви језици имају основне функције у својој стандардној библиотеци за подршку палиндрому. У случају да не постоји функција која би могла да подржи онда увек можемо да имамо петље попут, док, или за контролу структура попут Иф, елсе, пробијамо изјаве како бисмо реализовали ову функционалност.

Препоручени чланци

Ово је водич за Палиндроме у ЈаваСцрипту. Овдје ћемо расправити логичко објашњење с примјером како бисмо провјерили је ли низ / број палиндром. Такође можете погледати следеће чланке да бисте сазнали више -

  1. ЈаваСцрипт математичке функције
  2. Редовне изразе у ЈаваСцрипт-у
  3. ЈаваСцрипт МВЦ оквири
  4. Спајање сортирања у ЈаваСцрипт-у
  5. јКуери куериСелецтор | Примери за упитСелецтор
  6. Петље у ВБСцрипт са примерима
  7. Редовне изразе у Јави
  8. Примери уграђених функција Питхон-а

Категорија: