Check for Palindromes -- removing punctuation

I’m working on the “Check for Palindromes” challenge. My code works (though I’m open to any critique!) – I’m just wondering specifically if there’s a more efficient way of removing punctuation from the string, other than the very long return statement that I used? (I’m sure there is, I just couldn’t seem to find it!)

Thanks!

function palindrome(str) {


  splitStr = str.split("");
  var word = splitStr.filter(function(val) {
    return val !== " " && val !=="," && val !== "." && val !== "\\" && val !== "/" && val !== "_" && val !== "-" && val !== "(" && val !== ")";
  });
  newStr = word.join("");
  newStr = newStr.toLowerCase();
  pal = word.reverse();
  pal = word.join("");
  pal = pal.toLowerCase();


  if (newStr === pal) {
    return true;
  } else {
    return false;
  }
}

palindrome("_eye");

Link to the challenge:
https://www.freecodecamp.org/challenges/check-for-palindromes

There is definitely at least one way to do that using regular expressions, but I’m not sure how much more “efficient” it is in terms of computing time.

In case you are not familiar with using regular expressions, here is a short example:

const str = 'nyan!pa_su*?';
const filteredStr = str.replace(/[\W_]/g, '');

// The regular expression `\W` matches anything that is **not** an alphanumeric
// character underscore. That's why the character group `[\W_]` is used to also
// include underscore

console.log(filteredStr); // "nyanpasu"

Good luck! :smile:

EDIT: The advantage of filtering out anything that’s not alphanumeric with regular expression is that you don’t have to remove all punctuation (there are many more than just the ones you manually filtered out).

That’s exactly what I was looking for – thanks!!! Yes, I have a little familiarity with regular expressions, but hadn’t yet found the ‘[\W_]’ character group. That certainly makes it much less cumbersome in terms of writing the code. Point taken about “efficient” not necessarily applying in terms of computing time – good reminder to take that into account also!

Thanks so much!

Yeah, \W is a character that isnt a word character (not A-Z, a-z, 0-9 or _), but _ counts as a word character so you need to catch that as well. And the square brackets saying one of anything inside them (like [aeiou] would be one of a, e, i, o or u). So [\W_] is matching a character that isn’t a word character or is an underscore.

Thanks!! I’ve dealt with regular expressions once or twice, but the syntax is still rather foreign to me, so this helps a lot. Much appreciated!

OK, thanks, and sorry I didn’t think of that! This was my first time posting. :slight_smile: Will make sure to use spoiler tags in the future, or post less code!