Check if a string is a palindrome in JavaScript
Intermediate · 3 min read
A palindrome is text that reads the same backwards as forwards. "madam" is one. So is "A man, a plan, a canal: Panama", once you ignore the spaces, the commas and the capital letters. Checking for palindromes is a classic exercise because it teaches the most useful habit in string work: clean the input first, then the problem is easy.
In this tutorial you will write isPalindrome(text), which returns true or false, and then a second version that uses less memory. You need to know what a function, a string and a while loop are. Regular expressions are introduced gently below.
Reversing a string
Strings don't have a reverse method, but arrays do. So you split the string into an array of characters, reverse the array, and join it back:
console.log('hello'.split('').reverse().join('')); // olleh
If a word equals its own reverse, it is a palindrome.
Cleaning the text
"A man, a plan" doesn't equal its reverse as typed, because of the capital A, the spaces and the comma. So before comparing, we do two things:
- Make everything lowercase with
toLowerCase(). - Remove everything that isn't a letter or a digit.
For the second part we use replace with a regular expression. A regular expression is a small pattern for matching text, written between slashes. /[^a-z0-9]/g means:
[a-z0-9]matches one lowercase letter or digit.- The
^at the start of the brackets flips it: anything that is not a lowercase letter or digit. - The
gat the end means "every match", not just the first.
Replacing every match with '' deletes it.
Here is the exercise. Try it yourself first if you like, or follow the steps.
14 Check for a palindrome
fairDecide whether a piece of text reads the same backwards, ignoring case, spaces and punctuation.
Stuck? Three hints, smallest first
- 1. Normalise first: lowercase it and strip everything that is not a letter or digit.
- 2.
replace(/[^a-z0-9]/g, '')after lowercasing does the stripping. - 3. Comparing against the reversed copy is the simplest check; two pointers is the version without the extra allocation.
Step 1: compare a word with its reverse
function isPalindrome(text) {
return text === text.split('').reverse().join('');
}
console.log(isPalindrome('madam')); // true
console.log(isPalindrome('hello')); // false
console.log(isPalindrome('A man, a plan, a canal: Panama')); // false
The first two are right. The last one should be true, but the punctuation and capitals get in the way.
Step 2: write the cleaning function
Keep the cleaning in its own small function. That makes it easy to test, and both versions below can share it.
function normalise(text) {
return text.toLowerCase().replace(/[^a-z0-9]/g, '');
}
console.log(normalise('A man, a plan, a canal: Panama')); // amanaplanacanalpanama
Lowercase must come first. If you remove non-matching characters first, the capital A counts as "not a lowercase letter" and is deleted.
Step 3: clean, then compare
function isPalindrome(text) {
const clean = normalise(text);
return clean === clean.split('').reverse().join('');
}
console.log(isPalindrome('A man, a plan, a canal: Panama')); // true
console.log(isPalindrome('No lemon, no melon')); // true
console.log(isPalindrome('12321')); // true
console.log(isPalindrome('')); // true
Notice that almost all the work is in normalise. Once the text is in a known shape, the check is one line. An empty string counts as a palindrome, since it reads the same both ways.
Step 4: check without making a copy
The reverse in Step 3 builds a whole new string. For a word that doesn't matter. For a very long text there is a way that builds nothing extra: compare the first and last characters, then step inward from both ends.
function isPalindromeTwoPointer(text) {
const clean = normalise(text);
let left = 0;
let right = clean.length - 1;
while (left < right) {
if (clean[left] !== clean[right]) return false;
left++;
right--;
}
return true;
}
console.log(isPalindromeTwoPointer('madam')); // true
console.log(isPalindromeTwoPointer('hello')); // false
left and right are positions in the string. People call this the two-pointer technique. As soon as one pair doesn't match, the function returns false and stops. If the two positions meet in the middle without a mismatch, it is a palindrome. "hello" is rejected after a single comparison: h against o.
The full solution
The complete answer has normalise, both versions of the check, and runs five samples through isPalindrome. A check underneath confirms that the two versions agree on all of them. Press Run to see the output.
function normalise(text) {
return text.toLowerCase().replace(/[^a-z0-9]/g, '');
}
function isPalindrome(text) {
const clean = normalise(text);
return clean === clean.split('').reverse().join('');
}
// The two-pointer version: no reversed copy, so no extra allocation.
function isPalindromeTwoPointer(text) {
const clean = normalise(text);
let left = 0;
let right = clean.length - 1;
while (left < right) {
if (clean[left] !== clean[right]) return false;
left++;
right--;
}
return true;
}
const samples = [
'madam',
'A man, a plan, a canal: Panama',
'No lemon, no melon',
'hello',
'12321',
];
for (const s of samples) {
console.log(JSON.stringify(s), '->', isPalindrome(s));
}
Output
7 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 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a simple one', isPalindrome('madam'), true);
test('punctuation and case ignored', isPalindrome('A man, a plan, a canal: Panama'), true);
test('spaces ignored', isPalindrome('No lemon, no melon'), true);
test('a non-palindrome', isPalindrome('hello'), false);
test('digits work too', isPalindrome('12321'), true);
test('empty text counts as one', isPalindrome(''), true);
test('the two-pointer version agrees everywhere', samples.every((s) => isPalindrome(s) === isPalindromeTwoPointer(s)), true);
Almost all the work is in normalise, and that is the real lesson: most string problems become easy once the input is in a known shape. The two-pointer version does the same job walking inward from both ends, which avoids building a reversed copy — irrelevant for a word, worth having for a very long string.
Common mistakes
- Removing characters before lowercasing. The pattern
[^a-z0-9]then deletes every capital letter. - Forgetting the
gflag. Without it,replaceremoves only the first space or comma. - Using
while (left <= right). It still works, but it compares the middle letter with itself for no reason.left < rightis enough.
Try it yourself
- Write
longestPalindromeWord(sentence)that returns the longest word in a sentence that is a palindrome. - Make
isPalindromecount only letters, ignoring digits too. - Try "Été" with accents. What does
normalisedo with theé? (It is not ina-z.)