1

I want to be clear I'm not looking for solutions. I'm really trying to understand what is being done. With that said all pointers and recommendations are welcomed. I am woking through freecodecamp.com task of Check for Palindromes. Below is the description.

Return true if the given string is a palindrome. Otherwise, return false.

A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.

Note You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes.

We'll pass strings with varying formats, such as "racecar", "RaceCar", and "race CAR" among others.

We'll also pass strings with special symbols, such as "2A3*3a2", "2A3 3a2", and "2_A3*3#A2".

This is what I have for code right now again I'm working through this and using chrome dev tools to figure out what works and what doesn't.

function palindrome(str) {
  // Good luck!
str = str.toLowerCase();
 //str = str.replace(/\D\S/i);
str = str.replace(/\D\s/g, "");

for (var i = str.length -1; i >= 0; i--)
str += str[i];
}


palindrome("eye");

What I do not understand is when the below code is run in dev tools the "e" is missing.

str = str.replace(/\D\s/g, ""); "raccar"

So my question is what part of the regex am I miss understanding? From my understand the regex should only be getting rid of spaces and integers.

Stuti Rastogi
  • 1,162
  • 2
  • 16
  • 26
  • Paste your regexp into regex101.com and read the description carefully. –  May 18 '17 at 05:53

1 Answers1

0

/\D\s/g is replacing any character not a digit, followed by a space with "".

So, in race car, the Regex matches "e " and replaces it with "", making the string raccar

For digit, you need to use \d. I think using an OR would get you what you want. So, you may try something like /\d|\s/g to get a digit or a space.

Hope this helps in some way in your understanding!

Stuti Rastogi
  • 1,162
  • 2
  • 16
  • 26
  • ahh, ok thanks, that makes perfect since. I didn't realize I could use the or "|" in there. This should move me forward thanks. – David Stuard May 18 '17 at 05:38
  • What about the given test case of `2_A3*3#A2`? –  May 18 '17 at 05:55
  • [This post](http://stackoverflow.com/questions/4328500/how-can-i-strip-all-punctuation-from-a-string-in-javascript-using-regex) can help for that. – Stuti Rastogi May 18 '17 at 05:56