Palindrome challenge: Underscore in regex

Palindrome challenge: Underscore in regex
0

#1

Hi there!

Checking the resources online, I was able to come up with the following, but struggling with the Regular Expression portion in .replace. The underscore is still there

Output = ey_e

function palindrome(str) {

  var  newstr = str.toLowerCase().replace(/\W/,'');
  return newstr;
}

palindrome("#Ey_e");

How come the sample solution shows this RegEx with an underscore \W_? I don’t know what this means and tried looking online

Sample Solution

function palindrome(str) {
  return str.replace(/[\W_]/g, '').toLowerCase() ===
         str.replace(/[\W_]/g, '').toLowerCase().split('').reverse().join('');
}

Thanks for reviewing!


#2

Here’s a line from my code for this challenge:

 test_str = str.toLowerCase().replace(/\W|_/g,'')

You can see the | operator is there. So regex looks for W or _. The sample solution you list doesn’t include the or operator, so that might be problematic.

MDN offers a good explanation of that | operator within regex here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Hope that helps.


#3

In a more direct response to your code, I imagine regex would only replace instances of “W_” exactly. Obviously, ey_e doesn’t contain W_, so it wouldn’t do the replacement.


#4

Thanks for the quick response! Just a thing on top I noticed, are square brackets in the sample solution just optional to help the coder clarify what they want to be edited in the regex?


#5

Can’t give you a solid answer on that. I would assume so, as it doesn’t seem to match any of the uses of [ ] listed on the site i linked to above.


#6

The [\W_]means match any non-word character OR underscore character. The square brackets are a character set with an implied OR between each character. It is the equivalent writing \W|_ Why is the underscore there? Isn’t that considered a non-word character? Actually, regex treats the underscore as a valid word character, so that is why it has to be included in the regular expression.


#7

thanks for the explanation!


#8

Another good tool to help with regex are sites like: https://regexr.com/

Lots of good quick information while getting to test at the same time. I’ve personally learned a lot with some simple experimentation.


#9

Thank you for the link, this was definitely very clear and helpful compared to checking stackoverflow


#10

You’re very welcome. Yeah I went the stackoverflow route first hah.