WillKre
WillKre

Reputation: 6158

JavaScript Check for palindrome (spaces & punctuation included)

Trying to check for palindromes. I've checked other answers but none included punctuation & spaces.

"never odd or even" and "A man, a plan, a canal. Panama" Should return true but they don't.

   function palindrome(str) {
  if(str.replace(/[^\w\s]|_/g, "").toLowerCase() === str.replace(/[^\w\s]|_/g, "").toLowerCase().split("").reverse().join("")){
    return true;
  } else {
    return false;
  }
}
palindrome("eye");

Upvotes: 1

Views: 2346

Answers (5)

twig
twig

Reputation: 1

To work with unevenly spaced numbers in a string, punctuation and uppercase letters, you can use

let regex = /[^a-zA-Z0-9]/g;
  return (
    str.replace(regex, "").toLowerCase() ===
    str.replace(regex, "").toLowerCase().split("").reverse().join("")
  );

Upvotes: 0

Crystal McNeil
Crystal McNeil

Reputation: 1

This is similar to the above but reformatted:

function palindrome(str) {
    let regex = /[^a-zA-Z]/g;
    return str.replace(regex, '').toLowerCase() === str.replace(regex, '').toLowerCase().split('').reverse().join('');
}

Upvotes: 0

Aioros
Aioros

Reputation: 4383

I think you have an error in your RegEx. If you want to remove the spaces, you don't need that \s. Try changing:

str.replace(/[^\w\s]|_/g, "")

With

str.replace(/[^\w]|_/g, "")

Upvotes: 3

hasumedic
hasumedic

Reputation: 2167

You can try with a simpler regex which simply replaces any character that is not in the alphabet?

function palindrome(str) {
  if(str.replace(/[^a-zA-Z]/g, "").toLowerCase() === str.replace(/[^a-zA-Z]/g, "").toLowerCase().split("").reverse().join("")){
    return true;
  } else {
    return false;
  }
}

Upvotes: 0

leo.fcx
leo.fcx

Reputation: 6467

Use instead:

str.replace(/\W/g, "")

Which will replace any non-word char by empty string.

Upvotes: 2

Related Questions