Skip to main content
23. November 2021

Palindrome Checker

Prüfen, ob eine Zeichenkette ein Palindrom ist.

function palindrome(str) {
  /** Replace punctuation, space and case */
  let cleanedStr = str.replace(/[\s.,_-]*[\:\/\()]*/g, "").toLowerCase();
  /** Extract first and second part of string */
  let first = cleanedStr.substr(0, (cleanedStr.length - (cleanedStr.length % 2)) / 2);
  let second = cleanedStr.substr((cleanedStr.length + (cleanedStr.length % 2)) / 2);
  /** Check if flipped second part are equal to first part */
  return (second.split("").reverse().join("") === first) ? true : false;

console.log(palindrome("A man, a plan, a canal. Panama"));

palindrome("eye") should return true.

palindrome("_eye") should return true.

palindrome("race car") should return true.

palindrome("not a palindrome") should return false.

palindrome("A man, a plan, a canal. Panama") should return true.

palindrome("never odd or even") should return true.

palindrome("nope") should return false.

palindrome("almostomla") should return false.

palindrome("My age is 0, 0 si ega ym.") should return true.

palindrome("1 eye for of 1 eye.") should return false.

palindrome("0_0 (: /-\ :) 0-0") should return true.

palindrome("five|\_/|four") should return false.