Emmanuel Akinfulubi

JavaScriptString

Palindrome check ignoring punctuation in JavaScript

Intermediate · 3 min read

A palindrome reads the same forwards and backwards: racecar, level, 12321. Checking for one is a favorite beginner exercise, and the comparison takes a single line. The real work is in deciding what to ignore, so that a famous sentence like 'A man, a plan, a canal: Panama' counts.

In this tutorial you will write a strict palindrome check, then a cleaning step that removes capitals, spaces and punctuation, and look closely at what that cleaning throws away. You should know how to reverse a string with [...text].reverse().join(''). The regex we need is explained below.

The basic check

A string is a palindrome when it equals its own reverse. So the check is: reverse it, then compare with ===.

What "ignoring punctuation" means

To make 'A man, a plan, a canal: Panama' pass, you first clean the text: turn it to lowercase, then delete everything that isn't a letter or a digit. What is left, amanaplanacanalpanama, is a palindrome.

To delete characters we use replace with a regex. [a-z0-9] matches one lowercase letter or digit. A ^ just inside the opening bracket flips the meaning: [^a-z0-9] matches any character that is not a lowercase letter or digit. With the g flag and an empty replacement, every such character is removed.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

40 Palindromes, with and without punctuation

fair

Decide whether a string reads the same backwards. Make 'A man, a plan, a canal: Panama' count, and be explicit about what you threw away to get there.

Stuck? Three hints, smallest first
  1. 1. A strict comparison is one line; the work is in deciding what to ignore.
  2. 2. Lower-case and strip everything that is not a letter or digit first.
  3. 3. Check what your cleaning function does to a string that is all punctuation.

Step 1: the strict check

Step 1

const isStrictPalindrome = (text) => text === [...text].reverse().join('');
console.log(isStrictPalindrome('racecar')); // true
console.log(isStrictPalindrome('lagos'));   // false
console.log(isStrictPalindrome('Racecar')); // false

The first two work. The third fails because reversed it starts with a small r and ends with a capital R, and 'R' and 'r' are different characters.

Step 2: write the cleaning step

Step 2

const clean = (text) => text.toLowerCase().replace(/[^a-z0-9]/g, '');
console.log(clean('Racecar'));                        // 'racecar'
console.log(clean('A man, a plan, a canal: Panama')); // 'amanaplanacanalpanama'

Lowercase first, so capitals become letters that [a-z] keeps. Then remove spaces, commas, colons and anything else that isn't a letter or digit.

Step 3: check the cleaned text

Step 3

const clean = (text) => text.toLowerCase().replace(/[^a-z0-9]/g, '');
const isPalindrome = (text) => {
  const c = clean(text);
  return c === [...c].reverse().join('');
};
console.log(isPalindrome('Racecar'));                        // true
console.log(isPalindrome('A man, a plan, a canal: Panama')); // true
console.log(isPalindrome('lagos'));                          // false

We clean once, keep the result in c, and compare c with its reverse. It is the strict check from Step 1, run on cleaned text.

Step 4: digits and dates

Step 4

const clean = (text) => text.toLowerCase().replace(/[^a-z0-9]/g, '');
const isPalindrome = (text) => {
  const c = clean(text);
  return c === [...c].reverse().join('');
};
console.log(isPalindrome('12321'));      // true
console.log(isPalindrome('02/02/2020')); // true

Digits are kept, so numbers work. The slashes in the date are removed, leaving 02022020, which reads the same backwards.

Step 5: when everything is thrown away

Step 5

const clean = (text) => text.toLowerCase().replace(/[^a-z0-9]/g, '');
const isPalindrome = (text) => {
  const c = clean(text);
  return c === [...c].reverse().join('');
};
console.log(isPalindrome(''));    // true
console.log(isPalindrome('!!!')); // true
console.log(clean('!!!'));        // '' (an empty string)

An empty string reads the same backwards, so it passes. That is the usual convention. But '!!!' passes too, which may surprise you. Cleaning removed every character, and an empty string is a palindrome. If that is wrong for your program, reject text that cleans down to nothing before comparing; don't change the comparison.

Step 6: what [a-z] throws away

Step 6

const clean = (text) => text.toLowerCase().replace(/[^a-z0-9]/g, '');
console.log(clean('Ésope')); // 'sope'

é is not in a to z, so the cleaning step deleted it, and the word lost a letter. For English text this is fine. For names and other languages it changes the meaning. One option is to use \p{L} (any letter) and \p{N} (any digit) with the u flag instead of a-z0-9.

The full solution

Here is the complete answer: the strict check, clean, isPalindrome, a table printed for several inputs, and checks for digits, dates, empty input and accents. Press Run and compare the strict and cleaned columns.

The answer

const isStrictPalindrome = (text) => text === [...text].reverse().join('');

const clean = (text) => text.toLowerCase().replace(/[^a-z0-9]/g, '');

const isPalindrome = (text) => {
  const c = clean(text);
  return c === [...c].reverse().join('');
};

for (const t of ['racecar', 'Racecar', 'A man, a plan, a canal: Panama', 'lagos', '!!!']) {
  console.log(JSON.stringify(t).padEnd(34), 'strict:', String(isStrictPalindrome(t)).padEnd(6), 'cleaned:', isPalindrome(t));
}
console.log("clean('!!!') is", JSON.stringify(clean('!!!')), '<- which is why !!! passes');

Output


      
11 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 11 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

11 checks

test('a plain palindrome', isStrictPalindrome('racecar'), true);
test('a capital letter breaks the strict version', isStrictPalindrome('Racecar'), false);
test('cleaning first fixes that', isPalindrome('Racecar'), true);
test('punctuation and spaces are ignored once cleaned', isPalindrome('A man, a plan, a canal: Panama'), true);
test('digits count as characters', isPalindrome('12321'), true);
test('a date-shaped one', isPalindrome('02/02/2020'), true);
test('a non-palindrome is rejected', isPalindrome('lagos'), false);
test('the empty string passes, by convention', isPalindrome(''), true);
test('and so does a string of only punctuation, which may surprise you', isPalindrome('!!!'), true);
test('because cleaning removed everything', clean('!!!'), '');
test('the a-z class also strips accents, changing the meaning of the word', clean('Ésope'), 'sope');

Also in Function 2 and Recursion 10. Those two go after the algorithm — two pointers, and the recursive form. This one is about the cleaning step, which is where the real decisions are.

isPalindrome('!!!') returning true is not a bug, it is the consequence of a definition: after cleaning there is nothing left, and nothing reads the same backwards. If that answer is wrong for your caller, the fix is to reject input that cleans to an empty string, not to change the comparison.

[^a-z0-9] quietly deletes every accented letter, so 'Ésope' becomes 'sope'. For text that is not English, normalise and strip marks — exercise 44 — before filtering, or filter on \p{L} and \p{N} instead.

Common mistakes

  • Cleaning before lowercasing. [^a-z0-9] would delete every capital letter. Lowercase first.
  • Forgetting the g flag. Only the first space or comma is removed.
  • Not noticing what cleaning removes. Accented letters vanish with [a-z], and text of only punctuation passes.

Try it yourself

  1. Make isPalindrome('!!!') return false while '' still returns true.
  2. Check 'Was it a car or a cat I saw?'.
  3. Write isPalindrome again with two positions that move toward the middle instead of reversing the string.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.