Skip to content

Instantly share code, notes, and snippets.

@edoubart
Created March 26, 2019 22:00
Show Gist options
  • Save edoubart/6690ea10326f8ae8a6fbf1f9eb3bb281 to your computer and use it in GitHub Desktop.
Save edoubart/6690ea10326f8ae8a6fbf1f9eb3bb281 to your computer and use it in GitHub Desktop.
// Create a function that checks if a given string is a palindrome.
// A palindrome is text that reads the same forwards and backwards, disregarding puncation, spaces, etc.
const testStrings = [
"b",
"aba",
"abc", // FALSE
"abba",
"Race Car",
"Mr. Owl ate my metal worm",
"This is not a palindrome", // FALSE
"Ya! Pizza zip pizazz! I pay.",
"Doc, Note: I Dissent. A Fast Never Prevents A Fatness. I Diet On Cod.",
];
function isPalindrome(str) {
let result;
const cleanStr = str
.toLowerCase()
.match(/[A-Za-z]+/g)
.join('');
for (let index in cleanStr) {
if (cleanStr[index] === cleanStr[(cleanStr.length - index) - 1]) {
result = true;
}
else {
result = false;
break;
}
}
return result;
}
// Test Strings
testStrings.forEach(function(str) {
console.log(`isPalindrome:${isPalindrome(str)}`, str);
});
@johnnybenson
Copy link

Nice! Using match to get to an array is cool.

I forked your gist to show you a way to get there without the for loop.

https://gist.github.com/johnnybenson/836416442ab067fe72cad894abd212f0

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