Palindrome

JavaScript
Easy

Objective

Write a function that checks if a given word is a palindrome.

Requirements

  1. The function should be named isPalindrome

  2. It should accept a single string as an argument

  3. It should return true if the string is a palindrome, and false if otherwise

  4. It should ignore case, spaces, and punctuation

Check your solution

Tests

Function name is isPalindrome
isPalindrome("racecar")Expected:true
isPalindrome("lorem")Expected:false
isPalindrome("12345")Expected:false
isPalindrome("Was it a car or a cat I saw?")Expected:true

Solution

Here's how I would approach this, but keep in mind there might be other ways to solve this problem.

function isPalindrome(string) { // remove all non-alphanumeric characters const normalisedString = string.toLowerCase().replace(/[^a-zA-Z0-9]/g, ''); // reverse the string const reverseString = normalisedString.split('').reverse().join(''); // Check if they match return normalisedString === reverseString; }
Click to reveal