Exercise: Palindrome Check (JavaScript)
js-palindrome
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
- How would you handle punctuation or emoji?
- Whatβs the complexity of your solution?