Created
July 3, 2020 00:21
-
-
Save karol-majewski/e8166dfde4787fc1f60985cfe3c89a70 to your computer and use it in GitHub Desktop.
The easiest way to check if a string is a palindrome in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const isPalindrome = (phrase: string): boolean => { | |
const original = phrase.toLowerCase().replace(/[^A-Za-z0-9]/g, ''); | |
const reversed = original.split('').reverse().join(''); | |
return original === reversed | |
} | |
console.log( | |
isPalindrome("A man, a plan, a canal – Panama!") | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The regular expression:
/[^A-Za-z0-9]/g
means find non-alphanumeric characters globally. This part:
[^]
means "find not in this set" andA-Za-z0-9
means "alphanumeric characters".