Code Breakdown
Cleaning the string with regex and the replace function, non-characters and digits are removed before comparison.
The for loop reverses the string and creates a new string.
We compare the cleaned version to the reversed string and string length, to determine if the string is a palindrome.
// See The Code
function reverseString() {
// Get the user's word
let userWord = document.getElementById('tacoCat').value;
// Replace anything that is not a character or digit
const regex = /[^a-z0-9]/gi;
let cleanedWord = userWord.replace(regex, '').toLowerCase();
let reverseWord = '';
let start = cleanedWord.length - 1;
for (let i = start; i >= 0; i--) {
reverseWord += cleanedWord[i];
}
// Return results
let output = document.getElementById('result');
let msg = `${userWord} reversed is: `;
output.innerText = msg + reverseWord;
// Is this a palindrome
let palOutput = document.getElementById('isPalindrome');
let isPalindrome = cleanedWord === reverseWord;
// Must have 2 or more letters
if (isPalindrome && cleanedWord.length > 1) {
palOutput.innerHTML = `${userWord} is a palindrome.
${winner}`;
} else {
palOutput.innerHTML = `${userWord} is not a palindrome.
`;
}
}