Palindrome challenge: Underscore in regex

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;


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!

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:

Hope that helps.

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.

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?

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.

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.

1 Like

thanks for the explanation!

Another good tool to help with regex are sites like:

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

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

1 Like

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