Введение в палиндром в JavaScript

В общем смысле палиндром - это слово, такое, что когда мы читаем это слово символ за символом вперед, оно в точности совпадает со словом, образованным, когда то же слово читается с обратной стороны. Например: «уровень», «мадам» и т. Д. Здесь, когда слово «уровень» написано в обратном направлении, тогда и последнее сформированное слово будет «уровень». Эти виды слов, чисел, строки или серии символов, когда написаны на любом компьютерном языке. Тогда такая функциональность называется палиндромом. На языке программиста палиндром представляет собой последовательность символов, цифры, которые не меняются, даже когда они записаны в обратном направлении, образуя перестроенное слово. JavaScript предоставляет различные встроенные функции для реализации этой функциональности. У нас также могут быть циклы для получения того же результата. В этой статье мы собираемся подробнее изучить палиндром в клиентском языке программирования JavaScript.

Логическое объяснение палиндрома в JavaScript

Ниже приведен фрагмент кода, использующий встроенные функции javaScript, чтобы объяснить вам логику строки палиндрома:

Определена функция PTest (), в которой мы отправим строку, которую необходимо проверить на функциональность палиндрома. Если строка является палиндромом, мы должны получить текст, подтверждающий то же самое, в противном случае наоборот. Функция вызывается в конце после определения функции. Здесь reverse (), split (), join (), replace (), toLowerCase () являются встроенными функциями.

  • Replace (): эта функция заменит специальные символы и пробелы в строке.
  • toLowerCase (): эта функция будет в нижнем регистре вся строка.
  • Split (): функция Split разделит строку на отдельные символы.
  • Reverse (): функция Reverse перевернет строку, которая выводится из вышеуказанной функции. Это означает, что строка будет начинаться с последнего символа, считывающего символ за символом, до первого символа.
  • Join (): функция 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 */

Функция палиндрома также может быть написана с использованием циклов

В приведенном ниже коде цикл for используется для итерации цикла. При этом каждый раз, когда цикл выполняет символ спереди, сравнивается с символом на заднем конце. Если они совпадают, функция вернет логическое значение true. Этот цикл будет выполняться до половины длины входной строки. Потому что, когда мы сравниваем передний и задний символы строки, нам не нужно перебирать всю строку. Сравнение первой половины с последней половиной строки даст результат. Это делает программу компактной и быстрой.

Код:

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

Выходные данные этой программы будут иметь значение true, если входная строка этой программы представляет собой палиндром.

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

Ниже приведен подробный код в 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:

Выход:

Вывод

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

Рекомендуемые статьи

Это руководство по палиндрому в JavaScript. Здесь мы обсудим логическое объяснение с примером, чтобы проверить, является ли строка / число палиндромом. Вы также можете посмотреть следующие статьи, чтобы узнать больше -

  1. Математические функции JavaScript
  2. Регулярные выражения в JavaScript
  3. JavaScript MVC Frameworks
  4. Объединить Сортировать в JavaScript
  5. jQuery querySelector | Примеры для querySelector
  6. Циклы в VBScript с примерами
  7. Регулярные выражения в Java
  8. Примеры встроенных функций Python