Created
April 19, 2019 17:13
-
-
Save leolanese/fb176c3869ed082f32a99b133f3a55fd to your computer and use it in GitHub Desktop.
JavaScript Palindrome checker
This file contains hidden or 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
/* | |
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