Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 34 additions & 19 deletions apps/palindrome-checker/public/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,54 @@ const userInput = document.getElementById('text-input');
const checkPalindromeBtn = document.getElementById('check-btn');
const resultDiv = document.getElementById('result');

const checkForPalindrome = input => {
const originalInput = input; // Store for later output

if (input === '') {
alert('Please input a value');
return;
}
// Normalize text by removing non-alphanumeric characters and lowercasing
const normalizeText = str =>
str.replace(/[^A-Za-z0-9]/gi, '').toLowerCase();

// Return true if the given text is a palindrome
const isPalindrome = str => {
const normalized = normalizeText(str);
return normalized === [...normalized].reverse().join('');
};

const showResultMessage = message => {
// Remove the previous result
resultDiv.replaceChildren();

const lowerCaseStr = input.replace(/[^A-Za-z0-9]/gi, '').toLowerCase();
let resultMsg = `${originalInput} ${
lowerCaseStr === [...lowerCaseStr].reverse().join('') ? 'is' : 'is not'
} a palindrome.`;

const pTag = document.createElement('p');
pTag.className = 'user-input';
pTag.innerText = resultMsg;
pTag.textContent = message;
resultDiv.appendChild(pTag);

// Show the result.
// Show the result
resultDiv.classList.remove('hidden');
};

checkPalindromeBtn.addEventListener('click', () => {
const checkForPalindrome = rawInput => {
const originalInput = rawInput; // Preserve for output
const input = rawInput.trim();

if (!input) {
showResultMessage('Please input a value.');
return;
}

const resultMsg = `${originalInput} ${
isPalindrome(input) ? 'is' : 'is not'
} a palindrome.`;

showResultMessage(resultMsg);
};

const handleCheck = () => {
checkForPalindrome(userInput.value);
userInput.value = '';
});
};

checkPalindromeBtn.addEventListener('click', handleCheck);

userInput.addEventListener('keydown', e => {
if (e.key === 'Enter') {
checkForPalindrome(userInput.value);
userInput.value = '';
handleCheck();
}
});
});