Skip to content

Instantly share code, notes, and snippets.

@leolanese
Created April 19, 2019 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leolanese/fb176c3869ed082f32a99b133f3a55fd to your computer and use it in GitHub Desktop.
Save leolanese/fb176c3869ed082f32a99b133f3a55fd to your computer and use it in GitHub Desktop.
JavaScript Palindrome checker
/*
JavaScript Palindrome checker
*/
// Example
const string1 = 'level',
const string2 = 'Le, vel.';
// Function can take up to two strings
const isPalindrome = (str1, str2) => {
let string = str1
.replace(/[^\w]/gi, "") // replace all non-words characters
.toLowerCase(); // make all characters lower cased
if (str2) {
let reversedString = str2
.replace(/[^\w]/gi, "")
.toLowerCase()
.split('') // make an array
.reverse() // revers the array
.join(''); // make a string
return string == reversedString;
} else {
return string == string.split('').reverse().join('');
}
}
// Test
isPalindrome(string1, string2); // true
isPalindrome(string1); // true
isPalindrome(string2); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment