function isPalindrome(s: string): boolean {
const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return cleaned === cleaned.split('').reverse().join('');
}
console.log(isPalindrome('Racecar'));The function converts the string to lowercase and removes non-alphanumeric characters. 'Racecar' becomes 'racecar', which reads the same forwards and backwards, so the output is true.
Palindromes read the same forwards and backwards when ignoring case and non-alphanumeric characters. They can have odd or even length, include numbers, spaces, and punctuation.
function checkPalindrome(str: string): boolean { const reversed = str.split('').reverse().join(''); return str === reversed; } console.log(checkPalindrome(12321));
The function expects a string but receives a number. Calling split on a number causes a TypeError.
function countPalindromicSubstrings(s: string): number {
let count = 0;
for (let i = 0; i < s.length; i++) {
// Odd length palindromes
let left = i, right = i;
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++;
left--;
right++;
}
// Even length palindromes
left = i;
right = i + 1;
while (left >= 0 && right < s.length && s[left] === s[right]) {
count++;
left--;
right++;
}
}
return count;
}
console.log(countPalindromicSubstrings('aaa'));Palindromic substrings are: 'a', 'a', 'a', 'aa', 'aa', 'aaa' totaling 6.
function isUnicodePalindrome(s: string): boolean {
const normalized = s.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase();
return normalized === [...normalized].reverse().join('');
}
console.log(isUnicodePalindrome('AƱƱa'));The function removes diacritics and compares the string ignoring accents. 'AƱƱa' becomes 'anna' which is a palindrome, so output is true.
