← Back to Examples

Exercise: Palindrome Check (JavaScript)

js-palindrome
⭐ beginner ⏱️ 10 min

Write a function isPalindrome(s) that returns true if the string reads the same forwards and backwards (ignoring case and spaces), otherwise false.

palindrome.js

πŸ’‘ Hints

Hint 1: Normalize Input

Convert the input to lowercase and remove spaces: s.toLowerCase().replace(/\s+/g, '').

Hint 2: Compare With Reverse

Compute a reversed string and compare to the normalized string.

⚠️ Try the exercise first! Show Solution
function isPalindrome(s) {
  const norm = s.toLowerCase().replace(/\s+/g, '');
  const rev = [...norm].reverse().join('');
  return norm === rev;
}

πŸ§ͺ Tests

Run these tests locally with:

cargo test
View Test Code
// Run locally with: node palindrome.test.js
// (or paste into a Node REPL after defining isPalindrome)
const assert = require('assert');

assert.strictEqual(isPalindrome('racecar'), true);
assert.strictEqual(isPalindrome('Race Car'), true);
assert.strictEqual(isPalindrome('hello'), false);
assert.strictEqual(isPalindrome(''), true);
console.log('All JS tests passed');

πŸ€” Reflection