How to write a simple function to determine palindrome

Ask a question
2

How to write a simple function (less than 160 characters) that returns a boolean indicating whether or not a string is a palindrome?

Coin iconoffer bounty
add comment

1 Answer

1

The following one line function will return true if str is a palindrome; otherwise, it returns false.

function isPalindrome(str) {
  str = str.replace(/\W/g, '').toLowerCase();
  return (str == str.split('').reverse().join(''));
}

For example:

console.log(isPalindrome("level"));                   // logs 'true'
console.log(isPalindrome("levels"));                  // logs 'false'
console.log(isPalindrome("A car, a man, a maraca"));  // logs 'true'
add comment

Your Answer