Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created July 3, 2020 00:21
Show Gist options
  • Save karol-majewski/e8166dfde4787fc1f60985cfe3c89a70 to your computer and use it in GitHub Desktop.
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
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!")
)
@karol-majewski
Copy link
Author

karol-majewski commented Jul 3, 2020

The regular expression:

/[^A-Za-z0-9]/g

means find non-alphanumeric characters globally. This part: [^] means "find not in this set" and A-Za-z0-9 means "alphanumeric characters".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment