Check if a string is a palindrome

“Palindromes”, a Green belt challenge from the CurlyScript Dojo. It uses what Grade 7: Arrays: Lists of Things teaches, and 4 tests check your answer.

The challenge

Write isPalindrome(text) that returns true if the text reads the same forwards and backwards, ignoring case, spaces and punctuation.

Example
isPalindrome("Racecar")                 // true
isPalindrome("Was it a car or a cat I saw?")  // true
isPalindrome("hello")                   // false

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • isPalindrome("Racecar") gives true
  • isPalindrome("Was it a car or a cat I saw?") gives true
  • isPalindrome("hello") gives false
  • isPalindrome("a") gives true

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

First clean the text: lowercase it and keep only the letters a to z.

Hint 2

Then compare it with its reverse: clean.split("").reverse().join("").

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function isPalindrome(text) {
  let clean = "";
  for (const c of text.toLowerCase()) {
    if (c >= "a" && c <= "z") clean += c;
  }
  return clean === clean.split("").reverse().join("");
}

Learn what you need

This exercise uses what Grade 7: Arrays: Lists of Things teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning