Skip to content

Instantly share code, notes, and snippets.

@mrharel
Created November 8, 2018 12:32
Show Gist options
  • Save mrharel/1c9347a579f16a2eb9691359ba038c2e to your computer and use it in GitHub Desktop.
Save mrharel/1c9347a579f16a2eb9691359ba038c2e to your computer and use it in GitHub Desktop.
Palindromes in JavaScript
const word = "A man, a plan, a canal. Panama";
/*
* Checks if a string is a palindrome (as explained here: https://medium.freecodecamp.org/two-ways-to-check-for-palindromes-in-javascript-64fea8191fd7
* hard polindrome will not except string with white space.
*/
const palindrome = (w, hard = false) => {
const str = hard ? w : w.toLowerCase().replace(/[^a-zA-Z0-9]/g,"");
const left = str.substring(0, Math.floor(str.length/2));
const right = str.substring(Math.ceil(str.length/2)).split("").reverse().join("");
return left === right;
};
console.log(palindrome(word));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment