The Code
const getValues = () => {
let userString = document.getElementById('user-string').value;
let obj = checkForPalindrome(userString);
displayResults(obj);
}
const checkForPalindrome = (inputString) => {
var re = /[^A-Za-z0-9]/g;
let input = inputString.toLowerCase().replace(re, '');
var length = input.length;
let revString = '';
for (let i = input.length - 1; i >= 0; i--) {
let letter = input[i];
revString += letter;
}
let palindromeObj = {
isPalindrome: (revString == inputString),
reversedString: revString
}
return palindromeObj;
}
const displayResults = (obj) => {
let inputBox = document.getElementById('user-string');
let alertBox = document.getElementById('alert');
if (obj.isPalindrome) {
document.getElementById('palindrome').textContent = "You entered a Palindrome!";
document.getElementById('results').textContent = obj.reversedString;
alertBox.classList.remove('invisible', 'alert-danger');
alertBox.classList.add('alert-success');
inputBox.classList.remove('border', 'border-2', 'border-danger-subtle')
inputBox.classList.add('border', 'border-2', 'border-success-subtle')
}
else if (!obj.isPalindrome) {
document.getElementById('palindrome').textContent = "You did not enter a Palindrome!";
document.getElementById('results').textContent = obj.reversedString;
alertBox.classList.remove('invisible', 'alert-success');
alertBox.classList.add('alert-danger');
inputBox.classList.remove('border', 'border-2', 'border-success-subtle')
inputBox.classList.add('border', 'border-2', 'border-danger-subtle')
}
}
The code is structured in three functions
getValues
getValues()
is a function that grabs the text from the input element
and passes the text as a arguement to the function checkForPalindrome()
checkForPalindrome()
checkForPalindrome()
is a function that recieves the text from the method
getValues()
.
After the text is recieved, a regex is used to filter this text for anything characters that
are not a-z or 0-9 and replaces that text with nothing. The text is also transformed to lower case
before being used in a for loop. After the string is reversed with the for loop, a object called
palindromeObj
is
created with two properties: isPalindrome
which compares the user
input with the reversed string to determine whether this comparision is true or false and
reversedString
is the second
property which holds the user input that has been reversed. This object is returned and passed
to the displayResults()
function.
displayResults()
displayResults()
is a function that uses the object returned
from checkForPalindrome()
and displays whether or not
the user input is a palindrom or not, in a span tag.