Emmanuel Akinfulubi

JavaScriptFunction

Function to check a palindrome in JavaScript

Beginner · 4 min read

A palindrome is a word or phrase that reads the same backwards as forwards: madam, racecar, or the whole sentence "Was it a car or a cat I saw?". Checking for one is a classic beginner exercise and a common interview warm-up, because it mixes string cleaning, reversing and comparing.

In this tutorial you will write isPalindrome, a function that takes some text and answers true or false. Then you will write a second version that stops as soon as it finds a mismatch. You need to know what a function and a string are.

What counts as "the same backwards"

The exercise gives 'nurses run' as a palindrome. Read it backwards letter by letter and you get 'nur sesrun'. The letters match, but the space is in a different place. So the example is telling you something: spaces don't count. The same goes for capital letters and punctuation in "A man, a plan, a canal - Panama".

That gives a two-part plan:

  1. Clean the text: make it lower case and keep only letters and digits.
  2. Compare the cleaned text with its reverse.

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

2 Check a palindrome

easy

Test whether a string reads the same backwards. 'nurses run' should count, which tells you what to do about spaces.

Stuck? Three hints, smallest first
  1. 1. The example in the question has a space in it, so cleaning is part of the task.
  2. 2. Lower-case the text and remove anything that is not a letter or digit.
  3. 3. Compare against the reverse, or walk in from both ends, which stops early.

Step 1: the naive check

Reversing a string means spreading it into characters, reversing the array and joining it back:

Step 1

const naive = (text) => text === [...text].reverse().join('');
console.log(naive('madam'));      // true
console.log(naive('nurses run')); // false

'madam' works, but 'nurses run' fails because of the space. This is why cleaning comes first.

Step 2: clean the text

toLowerCase() turns every capital into a small letter. Then replace with a regular expression (a pattern for matching text) removes everything we don't want:

Step 2

const clean = (text) => text.toLowerCase().replace(/[^a-z0-9]/g, '');
console.log(clean('nurses run')); // 'nursesrun'
console.log(clean('Madam'));      // 'madam'
console.log(clean('Was it a car or a cat I saw?')); // 'wasitacaroracatisaw'

Reading the pattern /[^a-z0-9]/g piece by piece:

  • [a-z0-9] means "one letter from a to z, or one digit".
  • The ^ just inside the square brackets flips it: "any character that is not a letter or digit".
  • The g at the end means "every match", not just the first one.

So every space, comma, question mark and dash is replaced with nothing.

Step 3: compare the cleaned text

Step 3

const isPalindrome = (text) => {
  const c = clean(text);
  return c === [...c].reverse().join('');
};
console.log(isPalindrome('nurses run')); // true
console.log(isPalindrome('A man, a plan, a canal - Panama')); // true
console.log(isPalindrome('hello'));      // false

This is the readable version. It builds a whole reversed copy of the text, then compares the two.

Two small cases are worth knowing. A single letter is a palindrome, and so is the empty string '', because there is nothing that fails to match.

Step 4: walk in from both ends

Imagine checking a long text that isn't a palindrome. The first and last letters already differ, but Step 3 still reverses the whole thing first. A faster idea uses two pointers, which are just two index numbers:

  • i starts at the first character.
  • j starts at the last character.
  • Compare c[i] with c[j]. If they differ, stop: the answer is false.
  • Otherwise move i one step right and j one step left, and repeat until they meet.

Step 4

function isPalindromeTwoPointer(text) {
  const c = clean(text);
  let comparisons = 0;
  for (let i = 0, j = c.length - 1; i < j; i++, j--) {
    comparisons++;
    if (c[i] !== c[j]) return { result: false, comparisons };
  }
  return { result: true, comparisons };
}
console.log(isPalindromeTwoPointer('hello'));   // { result: false, comparisons: 1 }
console.log(isPalindromeTwoPointer('racecar')); // { result: true, comparisons: 3 }

The function returns an object so you can see how much work it did, not only the answer. For 'hello', h and o differ, so it stops after one comparison. For 'racecar' it needs only three, about half the length, because each comparison checks two letters at once. The middle e never needs checking.

The for line packs two counters into one loop: let i = 0, j = c.length - 1 sets both, i < j keeps going until they meet, and i++, j-- moves both.

The full solution

The panel has clean, the readable isPalindrome and the two-pointer version. It prints the answer for ten test phrases, then the comparison counts for 'hello' and 'racecar'. Press Run to see them.

The answer

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

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

// Two pointers. Same answer, and it stops at the first mismatch instead of
// building a whole reversed copy.
function isPalindromeTwoPointer(text) {
  const c = clean(text);
  let comparisons = 0;
  for (let i = 0, j = c.length - 1; i < j; i++, j--) {
    comparisons++;
    if (c[i] !== c[j]) return { result: false, comparisons };
  }
  return { result: true, comparisons };
}

const cases = ['madam', 'nurses run', 'A man, a plan, a canal - Panama', 'racecar',
  'hello', 'ab', 'a', '', '11/11/11 11:11', 'Was it a car or a cat I saw?'];

for (const t of cases) {
  console.log(JSON.stringify(t).slice(0, 34).padEnd(36), isPalindrome(t));
}
console.log('comparisons for "hello" :', isPalindromeTwoPointer('hello').comparisons, '<- stopped at the first mismatch');
console.log('comparisons for "racecar":', isPalindromeTwoPointer('racecar').comparisons);

Output


      
15 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 15 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

15 checks

test("'madam' is a palindrome", isPalindrome('madam'), true);
test("the example 'nurses run' works, so spaces are ignored", isPalindrome('nurses run'), true);
test('punctuation and case are ignored too', isPalindrome('A man, a plan, a canal - Panama'), true);
test('a question mark does not stop it', isPalindrome('Was it a car or a cat I saw?'), true);
test('digits and punctuation together', isPalindrome('11/11/11 11:11'), true);
test("'hello' is not", isPalindrome('hello'), false);
test('two different letters are not', isPalindrome('ab'), false);
test('a single letter is', isPalindrome('a'), true);
test('the empty string is, by convention', isPalindrome(''), true);
test('cleaning strips the space', clean('nurses run'), 'nursesrun');
test('and lower-cases', clean('Madam'), 'madam');
test('the two-pointer version agrees everywhere', cases.every((t) => isPalindromeTwoPointer(t).result === isPalindrome(t)), true);
test('it stops at the first mismatch', isPalindromeTwoPointer('hello').comparisons, 1);
test('and only needs half the length when it matches', isPalindromeTwoPointer('racecar').comparisons, 3);
test('so a long non-palindrome costs one comparison', isPalindromeTwoPointer('zebra' + 'a'.repeat(1000)).comparisons, 1);

Recursion 10 solves this by recursion; the point here is the shape of the function. The example in the question is 'nurses run', which has a space, so normalising is not an optional extra — it is the specification. Reading that out of the example rather than the prose is the skill.

The two-pointer version is the one to remember. It walks in from both ends and returns at the first mismatch, so a thousand-character non-palindrome costs one comparison rather than building a reversed copy of the whole string — the last assertion checks exactly that. It also needs only length / 2 comparisons when the answer is yes.

Common mistakes

  • Skipping the cleaning step. Without it, 'nurses run' and any sentence with capitals or punctuation comes out false.
  • Forgetting the g flag. replace(/[^a-z0-9]/, '') removes only the first space or comma, so longer phrases still fail.
  • Using i <= j in the two-pointer loop. It works, but when i and j meet in the middle it compares a letter with itself for no reason. i < j is enough.

Try it yourself

  1. Change clean so it keeps digits out too, then check whether '11/11/11 11:11' is still a palindrome. What happens, and why?
  2. Use isPalindrome with filter to keep only the palindromes from ['level', 'lagos', 'noon', 'abuja'].
  3. Count the comparisons the two-pointer version makes for 'abcdefedcba'. Predict the number before you run it.

Keep practising

Newsletter

New writing, when it lands.

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