Lesson 6 of 8

Palindromes

Goal

Text that reads the same both ways

01

Explanation

“Was it a car or a cat I saw?” reads the same forward and backward once you ignore spaces, punctuation and case. Checking it properly takes two steps: normalize the text first, then compare its two ends.

Normalizing means converting the letters to lowercase and removing everything that isn't a letter or a digit. The regex /[^\p{L}\p{N}]/gu handles the removal for every alphabet at once, and \p{…} only works with the u flag. Accents need one extra step: text.normalize('NFD') splits an accented letter like é or ή into its plain letter followed by a separate accent mark, and the same regex then removes the mark, because a mark isn't a letter. After that, use two pointers that start at the two ends and move toward each other comparing characters, stopping at the first mismatch, so you never need a reversed copy of the text.

Watch out: the regex /[^a-z0-9]/g deletes every letter outside a to z, accented letters included, so a Greek sentence turns into an empty string. An empty string is a palindrome, so the function answers “yes” for any Greek sentence.

02

Your task

Write normalize(text) to return the normalized text, and isPalindrome(text) to normalize the text, compare it with two pointers, and return true or false.

Checks

6 checks
  1. normalize removes spaces and punctuation and lowercases letters
  2. normalize keeps Greek letters without their accents
  3. An English palindrome returns true
  4. An accented palindrome returns true
  5. A Greek sentence that isn't a palindrome returns false
  6. Works with even and odd lengths
03

Hints

0/3
Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.