In: Computer Science
Palindrome Javascript
I am trying to write this javascript function to check if a number is Palindrome..
Palindrome means - a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
This is the code i have, but it doesnt work.
Code:
let convertButton = document.getElementsByClassName("btn")[0];
let userInput = document.getElementById("number").value;
let results = document.getElementById("result").value;
convertButton.addEventListener("click", function (event) {
event.preventDefault();
console.log(userInput);
if (validatePalidrome(userInput))
document.getElementById("result").innerHTML = "true";
else document.getElementById("result").innerHTML = "false";
});
function validatePalidrome(numbers) {
let userStringArray = userInput.split("");
let reverseUserInput = userStringArray.reverse();
let joinReverseString = reverseUserInput.join("");
if (userInput.localeCompare(joinReverseString) === 0) {
return true;
}
return false;
}
According to the given code,
Your approach is effiecient and good but needs a slight modification.
Including that modification, I have written the palindrom function using JavaScript.
Below are the Snippets:
Code Snippet:
Output Snippet:
String to be passed: mam, returns true
String to be passed: hi, returns False
Code in Text format:
function validatePalidrome(numbers)
// getting
inputString in numbers variable
{
let userStringArray =
numbers.split('');
// converting string to
array
let reverseUserInput =
userStringArray.reverse();
//
reversing the elements in the array
let joinReverseString = reverseUserInput.join(''); // again joining them as a string
if (numbers == joinReverseString)
// comparing the string with
original string in numbers
{
return true; // returns true if it is a palindrome
}
else
{
return false; // returns false if it is not a palindrome
}
}
I hope the above snippets, information, and the explanation will help you out!
Please comment if you have any queries/errors!
Thank you!