d
Amit DhamuSoftware Engineer
 

Check if phrase is a palindrome

2 minute read 00000 views

A Palindrome is a phrase or sequence which reads the same both forwards and backwards.

Here's a function we can use to determine that in Javascript.

const isPalindrome = input => {
  const phrase = String(input)
    .replace(/[^A-Z\d]/gi, '')
    .toLowerCase()
    .trim()

  return phrase === phrase.split('').reverse().join('')
}
  • String(input) - stringify the input. We are allowing this to accept numeric values too
  • /[^A-Z\d]/gi - remove all non alphanumeric characters from the input
  • Then lowercase and trim any whitespace

We compare this to the reversed version of the string (which has the same modifications as the original string) using split, reverse and join.

Test cases

describe('isPalindrome', () => {
  it.each([
    [909],
    [10_101],
    ['ama'],
    ['Ama'],
    ['amA'],
    ['a.ma'],
    ['Cigar? Toss it in a can. It is so tragic'],
    ['I did, did I?'],
    ['Ed, I saw Harpo Marx ram Oprah W. aside'],
    ['A man, a plan, a canal: Panama.'],
    ['Murder for a jar of red rum.'],
    ["Won't lovers revolt now?"],
    ['Wonton? Not now!'],
    ['Evil olive'],
    ["Dammit, I'm mad!"],
    ['Step on no pets'],
    ['Are we not drawn onward, we few, drawn onward to new era?'],
  ])('%p', phrase => {
    expect(isPalindrome(phrase)).toBeTruthy()
  })
})